Contenu | Rechercher | Menus

Annonce

Si vous avez des soucis pour rester connecté, déconnectez-vous puis reconnectez-vous depuis ce lien en cochant la case
Me connecter automatiquement lors de mes prochaines visites.

À propos de l'équipe du forum.

#26 Le 08/06/2010, à 17:33

mondai

Re : Enjoliver un fichier tex : vim ou emacs ?

merci bcp pour vos réponses, mais honnêtement je suis assez dépassé.

Je mets ici des photos de emacs avec ce que je souhaiterai avoir :
1 - La première, montre une chose très pratique que l'on a avec emacs, c'est la taille de la police qui change selon \chapter, \section, etc :

1276010345.png

Pour moi, c'est utile et ça permet "d'enjoliver" le fichier source.

2 - La seconde, c'est la possibilité d'avoir l'indentation des \footnotes avec une couleur différente, ça permet de rendre le texte plus clair :

1276010604.png

3 - Également une chose très pratique qu'il y avait avec emacs22 et que je n'ai pas trouvé avec emacs23, c'est le soulignement de tout ce qu'il y a dans \emph{}, ça contribue à "enjoliver" le fichier source et à le rendre plus clair.

Serait-il possible que l'un d'entre vous m'indique comment retrouver ça avec vim ? Ça peut paraître lourd si vous êtes habitués à vim donc je suis désolé si ma question est triviale, mais honnêtement moi je n'y arrive pas lol !

Par contre, pour le second point, je viens d'essayer en faisant copier-coller de ce que mettait manuel sur google-group et ça marche impec, un screenshot avec gvim pour montrer ça :

1276011162.png

Pour ceux qui utilisent TeXmaker ou Gedit (ou Kile, ce que j'utilisais avant), soit c'est moi qui ne sait pas utiliser ces logiciels soit ils sont incomplets en comparaison de emacs ou vim (ne serait-ce que l'indentation des \footnote je n'avais pas avec Kile, et j'ai regardé TeXmaker et Gedit et je n'ai pas trouvé)

Donc pour ceux qui utilisent TeXmaker ou gedit, je mets ici mon fichier .emacs :

(require 'tex-site)
;;################################################################################
;;                                            THUMBS-MODE
;;################################################################################
 (autoload 'thumbs "thumbs" "Preview images in a directory." t)

;;################################################################################
;;                                  ACTIVER LA COLORATION SYNTAXIQUE
;;################################################################################
(global-font-lock-mode t)
(setq font-lock-maximum-decoration t)
(setq font-lock-maximum-size nil)



;;################################################################################
;;                              SURLIGNAGE D'UNE RÉGION SÉLECTIONNÉE
;;################################################################################
(transient-mark-mode t)


;;################################################################################
;;                   POUR NE PAS AVOIR À TAPER EN ENTIER LA RÉPONSE YES/NO
;;################################################################################

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

;;################################################################################
;;                  NUMÉROTATION DES LIGNES EST DES COLONNES
;;################################################################################
;; Show line-number in the mode line
(line-number-mode 1)

;; Show column-number in the mode line
(column-number-mode 1)

;;################################################################################
;;                        POUR AVOIR L'HEURE DANS LA BARRE D'ETAT
;;################################################################################
(display-time)

(setq display-time-24hr-format t)  ;; Format 24 heures


;;################################################################################
;;                             SUPPORT DE LA SOURIS
;;################################################################################


(mouse-wheel-mode t)



;;################################################################################
;;              AUTO FILL MODE(retour a la ligne automatiquement)
;;################################################################################


(setq auto-fill-mode 1)

(add-to-list 'auto-mode-alist (cons "\\.php$" 'php-mode))

(defun toggle-setnu-mode ()
      (interactive)
      (if setnu-mode
        (setnu-mode -1)
        (setnu-mode 1)))



;;################################################################################
;;                    AFFICHAGE DES IMAGES ET FICHIERS COMPRESSÉS
;;################################################################################


(setq auto-image-file-mode t)
    (setq auto-compression-mode t)

(cond ((not (eq window-system 'x))
       (set-keyboard-coding-system 'latin-1)))

;;################################################################################
    ; METTRE TOUS LES FICHIERS DE SAUVEGARDE DANS UN SEUL RÉPERTOIRE
;;################################################################################




(setq backup-directory-alist
    '(("." . "~/.emacs-backup-files/")))

(cond ((not (eq window-system 'x))
       (set-keyboard-coding-system 'latin-1)))



;;################################################################################
;                          TEXT AND AUTO FILL MODE
;;################################################################################


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

;;################################################################################
;;                     CHEMIN COMPLET DANS LA BARRE DE TITRE ?
;;################################################################################

(setq frame-title-format "%S: %f")



;;################################################################################
 ;; POUR ENREGISTRER AUTOMATIQUEMENT LA POSITION DU CURSEUR QUAND ON QUITTE UN
;; FICHIER, ET Y RETOURNER AUTOMATIQUEMENT À LA RÉOUVERTURE
;;################################################################################

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


;;################################################################################
;; PARENTHESE MATCHING, PERMET DE VERIFIER AU FUR ET À MESURE DE LA FRAPPE QUE
;; L'ON FERME BIEN CE QUE L'ON OUVRE, AUSSI BIEN POUR LES PARENTHÈSES QUE LES
;; CROCHETS OU LES ACCOLADES.
;;################################################################################





(require 'paren)
(show-paren-mode 1)
(setq-default hilight-paren-expression t)




;;################################################################################
;; FERME AUTOMATIQUEMENT PARENTHÈSES, CROCHETS, GUILLEMETS
;; AU COURS DE LA FRAPPE
;;################################################################################




(defun insert-parentheses () "insert parentheses and go between them"
  (interactive)
(insert "()")
(backward-char 1))
(defun insert-brackets () "insert brackets and go between them" (interactive)
(insert "[]")
(backward-char 1))
(defun insert-braces () "insert curly braces and go between them" (interactive)
(insert "{}")
(backward-char 1))
(defun insert-quotes () "insert quotes and go between them" (interactive)
(insert "\"\"")
(backward-char 1))
(defun insert-french () "insert brackets and go between them" (interactive)
(insert "\\og  \\fg")
(backward-char 4))
(global-set-key "(" 'insert-parentheses) ;;inserts "()"
(global-set-key "[" 'insert-brackets)
(global-set-key "{" 'insert-braces)
(global-set-key "\"" 'insert-quotes)
(global-set-key "|" 'insert-french)



;;################################################################################
;;                  SUPPRIME TOUS LES ESPACES EN FIN DE LIGNE
;;################################################################################




(autoload 'nuke-trailing-whitespace "whitespace" nil t)

;;################################################################################
;;Visualiseurs
;;################################################################################

(setq TeX-output-view-style (quote (
      ("^pdf$" "." "xpdf %o")
      ("^ps$" "." "gv %o")
      ("^dvi$" "." "xdvi %o")
      )))

;;################################################################################
;; Codage des caractères
;;################################################################################

(set-terminal-coding-system 'utf-8)
;(set-keyboard-coding-system 'utf-8)
(set-language-environment 'utf-8)

;;################################################################################
;; Complétion automatique
;;################################################################################

(abbrev-mode t) ; completion automatique
(global-set-key (quote [S-tab]) (quote dabbrev-expand))

;;################################################################################
;; Menus etc...
;;################################################################################

;(tool-bar-mode 1)
(scroll-bar-mode 1)
(menu-bar-mode 1)

;;################################################################################
; 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)

;;################################################################################
; Supprimer les fichiers de sauvegarde en quittant.
; (vous savez, ces fameux fichiers dont le nom se termine par « ~ »)
;;################################################################################

(setq make-backup-files nil)

;;################################################################################
;; Syntaxe highlighting pour tout
;;################################################################################

(require 'font-lock)
(setq initial-major-mode
      (lambda ()
    (text-mode)
    (font-lock-mode)))
(setq font-lock-mode-maximum-decoration t
      font-lock-use-default-fonts t
      font-lock-use-default-colors t)

;;##################################################################################################
;;						ACCENTS
;;################################################################################################## 

    ; Accents
    ; Ils sont normalement supportés par votre distribution mais on ne sait jamais
;;##################################################################################################

    (setq selection-coding-system 'compound-text-with-extensions)

    ; Pour la console
;;##################################################################################################

    (if (not (eq window-system 'x))
    (standard-display-european t))

;;##################################################################################################
;;						KEYBOARD SHORTCUT
;;################################################################################################## 

;;(standard-display-european t)


;; Affiche le numéro de ligne et de colonne
;;##################################################################################################

(column-number-mode t)
(line-number-mode t)

;;##################################################################################################
    ; Thème - Affichage
;;##################################################################################################
    ; Installer avant color-theme
;;##################################################################################################

    (require 'color-theme)

;;##################################################################################################
    ; Mettre un titre aux fenêtres
;;##################################################################################################

    (setq frame-title-format '(buffer-file-name "Emacs: %b (%f)" "Emacs: %b"))

;;##################################################################################################
 ; Activer la coloration syntaxique
;;##################################################################################################

    (global-font-lock-mode t)

;;##################################################################################################
    ; Mettre un maximum de couleurs
;;##################################################################################################

    (setq font-lock-maximum-size nil)

;;##################################################################################################
    ; Mode texte en auto-fill par défaut
    ; (créé une nouvelle ligne à chaque fois que vous taper du texte)
;;##################################################################################################

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

;;##################################################################################################
    ; en Americain, les phrases (sentences) se terminent par deux espaces 
    ; ce comportement n'est pas souhaitable en francais
;;##################################################################################################

    (setq sentence-end-double-space nil)

  ; Divers

    ; Mettre tous les fichiers de sauvegarde dans un seul répertoire
    (setq backup-directory-alist
    '(("." . "~/.emacs-backup-files/")))

    ; Pour ne pas avoir à taper en entier la réponse yes/no
    (fset 'yes-or-no-p 'y-or-n-p)

    ; Affichage des images et fichiers compressés
    (setq auto-image-file-mode t)
    (setq auto-compression-mode t)

    ; Molette de la souris
    (defun up-slightly () (interactive) (scroll-up 5))
    (defun down-slightly () (interactive) (scroll-down 5))
    (global-set-key [mouse-4] 'down-slightly)
    (global-set-key [mouse-5] 'up-slightly)
    (defun up-one () (interactive) (scroll-up 1))
    (defun down-one () (interactive) (scroll-down 1))
    (global-set-key [S-mouse-4] 'down-one)
    (global-set-key [S-mouse-5] 'up-one)
    (defun up-a-lot () (interactive) (scroll-up))
    (defun down-a-lot () (interactive) (scroll-down))
    (global-set-key [C-mouse-4] 'down-a-lot)
    (global-set-key [C-mouse-5] 'up-a-lot)

    ; dictionnaire francais pour la correction orthographique ispell
    (setq ispell-dictionary "francais")

    ; format jour/mois/an pour le calendrier (M-x calendar)
    (setq european-calendar-style t)

    ; la semaine commence le lundi
    (setq calendar-week-start-day 1)

    ; jours et mois en francais dans le calendrier 
    (defvar calendar-day-abbrev-array
      ["dim" "lun" "mar" "mer" "jeu" "ven" "sam"])
    (defvar calendar-day-name-array
      ["dimanche" "lundi" "mardi" "mercredi" "jeudi" "vendredi" "samedi"])
    (defvar calendar-month-abbrev-array
      ["jan" "fév" "mar" "avr" "mai" "jun"
       "jul" "aou" "sep" "oct" "nov" "déc"])
    (defvar calendar-month-name-array
      ["janvier" "février" "mars" "avril" "mai" "juin"
       "juillet" "aout" "septembre" "octobre" "novembre" "décembre"])

    ; ----------------------------------------------------------------------
    ; PHP - HTML - CSS

    ; Manuel php en français
    (setq php-manual-url "http://www.nexen.net/docs/php/annotee/manual.php")

    ; Utiliser le html-helper-mode, http://www.gest.unipd.it/~saint/hth.html
    (autoload 'php-html-helper-mode "html-helper-mode" "html-helper-mode" t)

    ; Ajoute un mode pour éditer du php
    ; http://www.ontosys.com/reports/PHP.html
    (autoload 'php-mode "php-mode" "PHP editing mode" t)
    (add-to-list 'auto-mode-alist '("\\.php\\'" . php-mode))
    (add-to-list 'auto-mode-alist '("\\.php3\\'" . php-mode))
    (add-to-list 'auto-mode-alist '("\\.php4\\'" . php-mode))

    ; Utiliser le menu expert
    (setq html-helper-use-expert-menu t)
    ; Indenter automatiquement lorsque l'on appuie sur entrée
    (defun my-html-helper-load-hook ()
    (define-key html-mode-map (kbd "RET") 'newline-and-indent)
    )
    (add-hook 'html-helper-load-hook 'my-html-helper-load-hook)

    ; Utiliser PSGML pour les fichiers SGML, HTML, XML
    (autoload 'sgml-mode "psgml" "Major mode to edit SGML files." t)
    (autoload 'xml-mode "psgml" "Major mode to edit XML files." t)

(autoload 'reftex-mode               "reftex" "RefTeX Minor Mode" t)
(autoload 'turn-on-reftex            "reftex" "RefTeX Minor Mode" nil)
(autoload 'reftex-add-to-label-alist "reftex" "RefTeX Minor Mode" nil)
    
;;; To turn on RefTeX Minor Mode for all LaTeX files,
;;(add-hook 'LaTeX-mode-hook 'turn-on-reftex)   ; with AUCTeX LaTeX mode
(add-hook 'latex-mode-hook 'turn-on-reftex)   ; without AUCTeX LaTeX mode
    
;;; Replace AUCTeX functions
;;(setq reftex-plug-into-AUCTeX t) ;only for AUCTeX
;(load "tex-site")
(require 'tex-site) ;lance Auc-TeX
;trouve ds le fichier info d'auctex:
(setq TeX-auto-save t)
(setq TeX-parse-self t)
;(setq-default TeX-master nil)
; fin du fich info
(setq LaTeX-section-hook)
;(setq-default TeX-master nil) ;prompt pour le fichier-maitre
;lance RefTex avec Aux-TeX :
(add-hook 'LaTeX-mode-hook 'turn-on-reftex)
;pour accélerer RefTeX:
(setq reftex-enable-partial-scans t)
(setq reftex-save-parse-info t)
(setq reftex-use-multiple-selection-buffers t)
(setq reftex-plug-into-AUCTeX t)
; lance preview-latex
(load "preview-latex.el" nil t t)
;;Mode PDFLatex par défaut

(setq tex-pdf-mode t)

;(set-face-font 'default ' "VL-Gothic-Regular-14")
(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.
 '(TeX-PDF-mode t)
 '(TeX-view-program-selection (quote (((output-dvi style-pstricks) "dvips and gv") (output-dvi "xdvi") (output-pdf "xpdf") (output-html "xdg-open"))))
 '(column-number-mode t)
 '(custom-buffer-verbose-help nil)
 '(display-battery-mode t)
 '(display-time-mode t)
 '(scroll-bar-mode (quote right))
 '(show-paren-mode t)
 '(size-indication-mode t))
(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 "AliceBlue" :foreground "DarkSlateGray4" :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight normal :height 97 :width normal :foundry "unknown" :family "VL PGothic")))))
 
(add-hook 'LaTeX-mode-hook 'LaTeX-math-mode)

Ainsi que mon fichier .vimrc :

" REQUIRED. This makes vim invoke Latex-Suite when you open a tex file.
filetype plugin on

" For multi-byte character support (CJK support, for example):
"set fileencodings=ucs-bom,utf-8,cp936,big5,euc-jp,euc-kr,gb18030,latin1

" allow backspacing over everything in insert mode
set backspace=indent,eol,start

"set dir=~/.tmp                        " répertoire des fichiers temporaires
set ff=unix                           " suppression des ^M
set wrapscan                          " recherche en rond
set title                             " modifier le titre du terminal

" number of undos
set undolevels=200

set smarttab

" Set to auto read when a file is changed from the outside
set autoread

" IMPORTANT: win32 users will need to have 'shellslash' set so that latex
" can be called correctly.
" set shellslash
 
 "" Curseur à l'ancienne position
function! s:CursorOldPosition()
  if line("'\"") > 0 && line("'\"") <= line("$")
    exec "normal g`\""
  endif
endfunction
autocmd BufReadPost * silent! call s:CursorOldPosition()

function! LoadTemplate(name, extension)
  echohl Todo
  echo a:name
  echohl None
  let bou = expand('%:e')
  silent! execute '0r ' . $HOME . '/.vim/template/' . bou . '.tpl'
  silent! execute 'source ' . $HOME . '/.vim/template/autocompletion.vim'
endfunction
 
 " searching
set hlsearch        " When there is a previous search pattern, highlight all
                    " its matches.
set incsearch       " While typing a search command, show immediately where the
                    " so far typed pattern matches.
set ignorecase      " Ignore case in search patterns.
set smartcase       " Override the 'ignorecase' option if

set formatoptions=c,q,r,t " This is a sequence of letters which describes how
                    " automatic formatting is to be done.
                    "
                    " letter    meaning when present in 'formatoptions'
                    " ------    ---------------------------------------
                    " c         Auto-wrap comments using textwidth, inserting
                    "           the current comment leader automatically.
                    " q         Allow formatting of comments with "gq".
                    " r         Automatically insert the current comment leader
                    "           after hitting <Enter> in Insert mode. 
                    " t         Auto-wrap text using textwidth (does not apply
                    "           to comments)
                    
" shortcut for formatting paragraph
map	<C-J>	gqap
imap	<C-J>	<C-O>gqap
vmap	<C-J>	gq

" Some people prefer to use extrernal formatting utilities
" such as "fmt" or "par":
"nmap	<C-J>	!}fmt<CR>
"vmap	<C-J>	!fmt<CR>

" IMPORTANT: grep will sometimes skip displaying the file name if you
" search in a singe file. This will confuse Latex-Suite. Set your grep
" program to alway generate a file-name.
set grepprg=grep\ -nH\ $*
 
" make F11 "copy into clipboard"
":map <F11> "*y
 
" make F12 "paste from clipboard"
":map <F12> "*p
 
" write four spaces instead of tab
set tabstop=4
set shiftwidth=4
set expandtab
set softtabstop=4   " make the four spaces feel like a tab
 
" OPTIONAL: This enables automatic indentation as you type.
filetype indent on
set autoindent smartindent      " turn on auto/smart indenting

" switch on syntax highlight
"ing, use fortran free form
":let fortran_free_source=1
syntax on
 
"Personnalisation de la ligne de status
set statusline=%F%m%r%h%w\ [TYPE=%Y]\ [Line=%04l]\ [Col=%04v]\ [%p%%]
set laststatus=2

" met en surbrillance les espaces et les tabs en trop
highlight RedundantSpaces ctermbg=red guibg=red
match RedundantSpaces /\s\+$\| \+\ze\t\|\t/
" For all text files set 'textwidth' to 80 characters.
  autocmd FileType text setlocal textwidth=80

" visual bell?
set novisualbell
set t_vb=

" shortcut for formatting paragraph
map	<C-J>	gqap
imap	<C-J>	<C-O>gqap
vmap	<C-J>	gq

" Some people prefer to use extrernal formatting utilities
" such as "fmt" or "par":
"nmap	<C-J>	!}fmt<CR>
"vmap	<C-J>	!fmt<CR>

" custom status line
"hi User1 ctermfg=red   ctermbg=white
"hi User2 ctermfg=green ctermbg=white
"hi User3 ctermfg=blue  ctermbg=white
"set statusline=%1*[%02n]%*\ %2*%F%*\ %(\ %M%R%H)%)%=%3*Pos=<%l,%c%V>%*
 
" Permet de se repérer dans les parenthèses & Co.
set showmatch

" Superbe menu de complétion \o/
set wildmenu
set wildignore=*.o,*~,*.cmo,*.cmi,*.a,*.cmx,*.cmxa

"Autorisation de remonter ou descendre d'une ligne avec les flèches
"gauche ou droite
set whichwrap=b,s,<,>,[,]
 
" show cursor position all the time
set ruler
 
" line numbering
set number
 
" wrap at word
set lbr
 
" nice colours
colorscheme habilight
colors habilight
 
set enc=utf-8

" ---------------------------------------------------------------------------
" spelling...
set spell

" correction orthographique
map <silent> <F7> "<Esc>:silent setlocal spell! spelllang=fr<CR>"
map <silent> <F8> "<Esc>:silent setlocal spell! spelllang=en<CR>"

if v:version >= 700
  let b:lastspelllang='en'
  function! ToggleSpell()
    if &spell == 1
      let b:lastspelllang=&spelllang
      setlocal spell!
    elseif b:lastspelllang
      setlocal spell spelllang=b:lastspelllang
    else
      setlocal spell spelllang=en
    endif
  endfunction

  nmap <LocalLeader>ss :call ToggleSpell()<CR>

  setlocal spell spelllang=en
  setlocal nospell
endif

augroup END

set mousemodel=popup
set spellfile=~/.spellfile.add

"set winheight=999               " maximize split windows
"set winminheight=0              " completely hide other windws

" ---------------------------------------------------------------------------
" mouse settings
set mouse=a                     " mouse support in all modes
set mousehide                   " hide the mouse when typing text

" make tab in v mode keep highlighting
vmap <tab> >gv
vmap <s-tab> <gv
 
function! SetupLatex(arg)
    if a:arg == 'pdf'
        let a:targetformat = 'pdf'
    elseif a:arg == 'dvi'
        let a:targetformat = 'dvi'
    elseif a:arg == ''
        if g:Tex_DefaultTargetFormat == 'dvi'
            let a:targetformat = 'pdf'
        else
            let a:targetformat = 'dvi'
        endif
    endif
 
    if a:targetformat == 'dvi'
        " target for latex
        let g:Tex_DefaultTargetFormat = 'dvi'
        " inverse search -- start gvim as "gvim --servername xdvi"
        "let g:Tex_CompileRule_dvi = 'latex --src -interaction nonstopmode $*'
        "let g:Tex_CompileRule_dvi = 'latex --src -interaction nonstopmode $*; if pgrep -fx "xdvi.bin -name xdvi -editor gvim --servername vim --remote +%l %f $*"; then wmctrl -a "xdvik:  $*"; fi;'
        let g:Tex_CompileRule_dvi = 'latex --src -interaction nonstopmode $*; if pgrep "xdvi.bin"; then wmctrl -a "xdvik:"; fi;'
        let g:Tex_ViewRule_dvi = 'xdvi -editor "gvim --servername vim --remote +\%l \%f" -watchfile 1 $* &'
        map \ld :execute '!xdvi -editor "gvim --servername '.v:servername.' --remote +\%l \%f" -sourceposition '.line(".").':'.col(".").expand("%").' '.expand(Tex_GetMainFileName(':r')).'.dvi >/dev/null&'<CR><CR>
    else " pdf
        let g:Tex_DefaultTargetFormat = 'pdf'
        let g:Tex_CompileRule_pdf = 'pdflatex -interaction nonstopmode $*; if pgrep -fx "xpdf -remote vimlatex $*.pdf"; then xpdf -remote vimlatex -reload && wmctrl -a "Xpdf: $*.pdf"; fi;'
        "let g:Tex_CompileRule_pdf = 'pdflatex -interaction nonstopmode $*; if pgrep -fx "xpdf -remote vimlatex $*.pdf"; then xpdf -remote vimlatex -reload -raise; fi;'
        let g:Tex_CompileRule_pdf = 'pdflatex -interaction nonstopmode $*; if pgrep -fx "xpdf -remote vimlatex $*.pdf"; then xpdf -remote vimlatex -reload && wmctrl -a "Xpdf: $*.pdf"; fi;'
        let g:Tex_ViewRule_pdf = 'xpdf -remote vimlatex'
    endif
endfunction
 
if exists("myTeXtarget")
    :call SetupLatex(myTeXtarget)
    let g:Tex_MultipleCompileFormats = 'dvi,pdf'
 
    " include cross referenced references also if they are cross referenced less
    " than two times
    let g:Tex_BibtexFlavor = 'bibtex -min-crossrefs=1'
    " let the cursor in the tex buffer if an error occured
    let g:Tex_GotoError = 0
    let g:Tex_IgnoredWarnings =
                \'Underfull'."\n".
                \'Overfull'."\n".
                \'specifier changed to'."\n".
                \'You have requested'."\n".
                \'Missing number, treated as zero.'."\n".
                \'There were undefined references'."\n".
                \'Latex Warning:'."\n".
                \'LaTeX Warning:' " float stuck
                "\'Citation %.%# undefined'
    let g:Tex_IgnoreLevel = 8
endif
 
" font
set guifont=DejaVu\ Sans\ Mono\ 10
 
" manual folding
set foldmethod=marker
"set commentstring=\ #\ %s
 
" to cycle with ctrl-N trough all labels
set iskeyword+=:
 
" Sauvegarde rapide du fichier actuel
map <F2> :w<CR>
imap <F2> <ESC>:w<CR>

" Terminal
map <S-F2> :!xterm &<CR><CR>
imap <S-F2> <ESC>:!xterm &<CR><CR>

" Gestionnaire de fichiers graphique
map <F2>t :!pcmanfm & <CR><CR>
map <F2>t <ESC>:!pcmanfm &<CR><CR>

" UCS Transformation Format 8 bits : léger et universel
set encoding=utf-8


" control-left & right arrows switch between tabs
map <c-Left> :tabp<CR>
map <c-Right> :tabn<CR>
 
" keep at least 5 lines above/below cursor
set scrolloff=5
 
" show me where i am
set cursorline


"" Racourcis à la firefox
map <C-t>     :tabnew<cr>
map <C-left>  :tabnext<cr>
map <C-right> :tabprevious<cr>
map <C-o> :e
 
" completion http://vim.wikia.com/wiki/Omni_completion
set ofu=syntaxcomplete#Complete
" http://vim.wikia.com/wiki/VimTip1386
set completeopt=longest,menuone
inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
inoremap <expr> <C-n> pumvisible() ? '<C-n>' :
  \ '<C-n><C-r>=pumvisible() ? "\<lt>Down>" : ""<CR>'
inoremap <expr> <M-,> pumvisible() ? '<C-n>' :
  \ '<C-x><C-o><C-n><C-p><C-r>=pumvisible() ? "\<lt>Down>" : ""<CR>'
" instead of control x control o: tab http://vim.wikia.com/wiki/VimTip102
function! CleverTab()
    if pumvisible()
        return "\<C-N>"
    endif
    if strpart( getline('.'), 0, col('.')-1 ) =~ '^\s*$'
        return "\<Tab>"
    elseif exists('&omnifunc') && &omnifunc != ''
        return "\<C-X>\<C-O>"
    else
        return "\<C-N>"
    endif
endfunction
inoremap <Tab> <C-R>=CleverTab()<CR>

" ---------------------------------------------------------------------------
"  configure calendar
let g:calendar_monday = 1

"------------------------------------------------------------------------------
"----------------------------------------------------------------------------
" Vim indent file
" mpg-customized
"
" Language: LaTeX
" Was:      http://www.unet.univie.ac.at/~a9925098/vim/indent/tex.vim
"

if exists("b:did_indent") | finish
endif
let b:did_indent = 1

setlocal indentexpr=GetTeXIndent()
setlocal nolisp
setlocal nosmartindent
setlocal autoindent
setlocal indentkeys+=},=\\item,=\\bibitem,=\\else,=\\fi,=\\or,=\\]

" Only define the function once
if exists("*GetTeXIndent") | finish
endif

function GetTeXIndent()

  " Find a non-blank line above the current line.
  let lnum = prevnonblank(v:lnum - 1)

  " At the start of the file use zero indent.
  if lnum == 0
    return 0
  endif

  let ind = indent(lnum)
  let line = getline(lnum)             " last line
  let cline = getline(v:lnum)          " current line

  " Remove the commented part of the lines
  let line = substitute(line, '%.*$', '', '')
  let cline = substitute(cline, '%.*$', '', '')

  " Add a 'shiftwidth' after beginning of environments.
  " Don't add it for \begin{document}, \begin{verbatim}, etc.
  if line =~ '\\begin{'  && line !~ 'verbatim'
        \ && line !~ 'document' && line !~ 'lstlisting'

    let  ind += &sw

  endif

  " Subtract a 'shiftwidth' when an environment ends
  if cline =~ '\\end{' && cline !~ 'verbatim'
        \&& cline !~ 'document' && cline !~ 'lstlisting'

    let  ind -= &sw

    " Remove another sw for item-environments
    if cline =~ 'itemize\|description\|enum\|thebibliography'
      let  ind -= &sw
    endif

  endif

  " Same for short display math environment \[ ... \]
  if line =~ '\\\['
    let ind += &sw
  endif

  if cline =~ '\\\]'
    let ind -= &sw
  endif

  " Special treatment for 'item'
  " ----------------------------

  " '\item' or '\bibitem' itself:
  if cline =~ '^\s*\\\(bib\)\=item' && line !~ '^\s*\\begin{'
    let  ind -= &sw
  endif

  " lines following to '\item' are intented once again:
  if line =~ '^\s*\\\(bib\)\=item'
    let  ind += &sw
  endif

  " Special treatment for 'if' constructs
  " -------------------------------------

  if line =~ '^\s*\(\\if\|\\expandafter\\if\|\\else\>\|\\or\>\)'
              \ && line !~ '\\fi\>'
    let ind += &sw
  endif

  if cline =~ '^\s*\(\\else\>\|\\or\>\|\\fi\>\)'
    let ind -= &sw
  endif

  " { and } (must be done at end, since it modifies line)
  " -------

  let line = substitute(line, '\\{\|\\}', '', 'g')
  let ind += &sw * strlen(substitute(line, '[^{]', '', 'g'))
              \ - &sw * strlen(substitute(line, '[^}]', '', 'g'))

  return ind

endfunction

" vim: set sw=2 ts=2:

Et je vous conseille de jeter un oeil à emacs et vim pour éditer des fichiers tex après avoir mis les fichiers .emacs et .vimrc dans votre ~/, et installé emacs-snapshot et gvim, ça vaut le coup !

Edit : pour mon fichier .vimrc ça peut paraître être le bordel mais j'ai fais ça vite fait tout à l'heure lol

Dernière modification par mondai (Le 08/06/2010, à 17:43)

Hors ligne

#27 Le 08/06/2010, à 17:46

Airballman

Re : Enjoliver un fichier tex : vim ou emacs ?

MErci poulet,

Comme je l'ai dit, j'utilise TExmaker au boulot.
A la maison, emacs et vim c'est selon mon humeur tongue

Mais j'ai appris plein de trucs au fil de ce post !
C'est super en fait, je vais relire tout ca au calme ce soir smile
Le speech sur les text objects notamment, j'avais mal compris la porté"e en postant tout à l'heure. Ca a lair ultra puissant!

Je ne savais pas que l'on pouvait rendre le code source latex sexy comme ca avec emacs. C ton .emacs qui fait tout ca? Il marche uniquement pour du Latex?

J'utilise souvent emacs pour faire du vhdl, si je recupere ton .emacs ca risque pas de mettre le bazar?

Dernière modification par Airballman (Le 08/06/2010, à 17:47)

Hors ligne

#28 Le 08/06/2010, à 17:48

Luc Hermitte

Re : Enjoliver un fichier tex : vim ou emacs ?

Il y a trop de choses dans ton .vimrc.
La config de vim, c'est un ensemble de fichiers spécialisés.

Hors ligne

#29 Le 08/06/2010, à 19:27

mondai

Re : Enjoliver un fichier tex : vim ou emacs ?

MErci poulet,

mdrrr

Je ne savais pas que l'on pouvait rendre le code source latex sexy comme ca avec emacs. C ton .emacs qui fait tout ca? Il marche uniquement pour du Latex?

En réalité c'est par défaut que c'est comme ça, moi je sais pas faire, et pour vim c'est pareil je sais pas faire, cest pour ça que je demande lol ! même après avoir passé des heures sur internet j'ai pas trouvé. Et il y a bien une personne (que j'ai cité dans mon premier post) qui a demandé, mais il n'a pas eu de réponse...

Par contre la couleur (vu que le but c'est d'utiliser su le long terme je prépare toutes les configurations maintenant pour être tranquille après) ça c'est moi, et tt le reste qu'il y a dans le .emacs j'ai piqué à droite et à gauche sur internet.

@Luc Hermitte

Il y a trop de choses dans ton .vimrc.
La config de vim, c'est un ensemble de fichiers spécialisés.

J'avais fais ça pour ne rien oublié (et je viens juste de pensé que j'ai quand même oublié un truc, rajouter un truc dans mon .vimrc pour les é lol) mais en fait avant d'avoir fait un .vimrc par moi-même (enfin en piquant aussià droite à gauche sur internet sur ceux des autres), la question que je posais était toujours valable aussi...
La seule chose que j'ai réussi à faire par moi-même, c'est le colorscheme, mais c'est pas ce que je voulais lol !

Je sais pas comment me prennent ce qui me lisent, je voudrais pas avoir l'air d'un enfant gâté qui demande l'impossible, si vous me dites que ce que je voudrais avoir est impossible à faire y a pas de problème. J'hésite entre emacs et vim uniquement pour écrire en latex, mon but est surtout d'essayer les 2 autant que possible sur une courte période pour me faire mon idée.

Ma question sur les caractéristique de emacs que j'ai énoncé précédemment et que j'aimerai retrouver sur vim est surtout là pour essayer de trouver quel est le logiciel que je vais utiliser sur le long terme, qui me permettra d'avoir le meilleur de tous les mondes (kile, texmaker, gedit, emacs, vim, etc) en quelque sorte.

Hors ligne

#30 Le 09/06/2010, à 02:17

mondai

Re : Enjoliver un fichier tex : vim ou emacs ?

re-salut,

juste pour dire que pour emacs j'ai trouvé comment on fait pour modifier l'apparence du fichier source :

M-X customize-face

c'était tout con (j'ai presque honte d'avoir dit que je ne savais pas comment on fait avec emacs).

mais je ne sais toujours pas comment faire avec vim lol ! Bon sinon si je suis un peu lourd je peux comprendre, j'essaierai de me débrouiller par moi-même au pire en demandant sur une mailinglist, et je reviendrai poster ici comment on fais avec vim en cas où y en aurait que ça intéresse.

une ptit capture d'écran pour montrer les \emph{} avec emacs big_smile :
1276042623.png

Dernière modification par mondai (Le 09/06/2010, à 02:18)

Hors ligne

#31 Le 09/06/2010, à 04:56

Luc Hermitte

Re : Enjoliver un fichier tex : vim ou emacs ?

Tout mettre dans ton .vimrc ne marchera pas correctement.
Il y a des politiques de chargement de fichiers telles qu'il faut garder les règles de nommage et les lieux de stockage des fichiers que tu trouves sur le net.

Hors ligne

#32 Le 09/06/2010, à 15:04

Pylades

Re : Enjoliver un fichier tex : vim ou emacs ?

Je ne pense pas que Vim puisse changer la taille du texte en fonction de la syntaxe (en tous cas pas dans une console) ; mais il y a un plugin pour LaTeX : « vim-latexsuite ». Je n’ai pas testé, mais c’est peut-être sympa.


“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets into the way, and using a goto is just much clearer.”
                Linus Torvalds – 12 janvier 2003

Hors ligne

#33 Le 09/06/2010, à 22:51

mondai

Re : Enjoliver un fichier tex : vim ou emacs ?

Pylad :
Je ne pense pas que Vim puisse changer la taille du texte en fonction de la syntaxe (en tous cas pas dans une console) ; mais il y a un plugin pour LaTeX : « vim-latexsuite ». Je n’ai pas testé, mais c’est peut-être sympa.

Ok merci ! bon ben de tt façon j'ai cherché et jai pas trouvé, je suis mort !

Mais essayer vim aura été une bonne expérience, là je cherche comment faire pour avoir les "folding" (quelqu'un saurait comment on dit en français ? lol) que j'avais avec vim pour les avoir avec emacs !

après j'aurai le meilleur des 2 mondes, et mes fichiers sources seront lisibles sans difficulté et j'aurai encore mieux que kile, texmaker et gedit ! tongue

Dès que je finis je posterai mon init.el spécial LaTeX pour ceux que ça intéresserait !

Luc Hermitte :
Tout mettre dans ton .vimrc ne marchera pas correctement.
Il y a des politiques de chargement de fichiers telles qu'il faut garder les règles de nommage et les lieux de stockage des fichiers que tu trouves sur le net.

Ok merci ! Bon a priori c'est pas faisable ce que je demandais, ou alors c'est difficile à faire et personne ne sait (ou pas ceux qui m'ont lu en tt cas).

Donc a priori j'utiliserai emacs au lieu de vim. Mais j'ai retenu ton conseil pour vim en l'appliquant pour emacs. Donc au lieu de faire un .emacs dans le home, j'ai fais un dossier lips placé ainsi : ~/.emacs.d/lips, et j'ai effacé mon fichier .emacs pour le remplacer par un init.el dans ~/.emacs.d. C'est ce que tu conseillais de faire si j'ai bien compris (et si j'ai bien transposé).

En tt cas les raccourcis clavier avec vim étaient cool, vim va me manquer sniff lol

Dernière modification par mondai (Le 09/06/2010, à 22:52)

Hors ligne

#34 Le 10/06/2010, à 09:02

omc

Re : Enjoliver un fichier tex : vim ou emacs ?

mondai a écrit :

Dès que je finis je posterai mon init.el spécial LaTeX pour ceux que ça intéresserait !

Oui, ça m'intéresse !!!

Hors ligne

#35 Le 10/06/2010, à 11:53

Le Farfadet Spatial

Re : Enjoliver un fichier tex : vim ou emacs ?

Salut à tous !

   Tiens, je l'ai laissé passé celui-là !

mondai a écrit :

Farfadetdel'espace (ou "Farfadet spatial" j'ai oublié son pseudonyme)

C'est pourtant simple : Le Farfadet Spatial !

   Cela dit, je te soupçonne d'avoir fait cette erreur juste pour m'obliger à répondre, espèce de vil fourbe !

conseillait d'essayer les 2 pour se faire son propre avis par soi-même

Je persiste et je signe : il est bon de tester un peu en profondeur les deux, pour voir quelle logique nous correspond le plus. Après, l'un comme l'autre est fortement paramétrable.

   Pour ma part, j'utilise Emacs, parce que je n'ai jamais réussi à me faire à Vim. Donc, pour LaTeX (par exemple pour les 200 pages de ma thèse), j'utilise Emacs et j'en suis très satisfait. Du coup, je laisse Luc HERMITTE, grand spécialiste de Vim, donner les détails pour l'utiliser de manière à éditer efficacement un document LaTeX.

   À bientôt.

   Le Farfadet Spatial
   (retiens bien ce nom !)

Hors ligne

#36 Le 11/06/2010, à 11:19

mondai

Re : Enjoliver un fichier tex : vim ou emacs ?

Salut,

Je suis en train de finaliser mon installation, est-ce que ceux qui ont utilisé emacs ou vim pour écrire une thèse avec latex pourraient poster leur .emacs ou init.el pour les utilisateurs de emacs (et d'autres fichiers qui leur sembleraient approprié de poster).

Je serai aussi intéressé par le .vimrc pour les utilisateurs de vim (avec aussi les fichiers appropriés que vous avez pour rédiger une thèse). Ça serait pour m'inspirer voir si j'ai oublié quelque chose ou si un truc utile m'échapperait.

Cela dit, je te soupçonne d'avoir fait cette erreur juste pour m'obliger à répondre, espèce de vil fourbe !

En particulier ta configuration m'intéresserait bcp, Farfadet de l'espace,de la galaxie ou je sais plus trop quoi mdrrr ! tongue

Hors ligne

#37 Le 11/06/2010, à 12:37

Le Farfadet Spatial

Re : Enjoliver un fichier tex : vim ou emacs ?

Salut à tous !

mondai a écrit :

En particulier ta configuration m'intéresserait bcp

Mauvaise nouvelle : l'ordinateur du laboratoire a rendu l'âme deux jours avant que je fasse la récupération -- or, pour des problèmes de relations entre mon ancien directeur de thèse et le service informatique, rien n'était sauvegardé... Du coup, je n'ai rien récupéré. Cela dit, ça ne t'aurait sans doute pas beaucoup intéressé, parce que, si j'utilise l'indentation automatique, je ne suis pas un fan, en LaTeX, de l'enjolivement syntaxique.

   Au fait, j'ai vu une erreur dans une de tes saisies d'écrans : après « \fg », pour t'assurer qu'il y aura bien un espace, tu devrais mettre « \ », ce qui donne ceci : « \fg\ ». Le tilde (« ~ »), c'est pour l'espace insécable. Avec ton exemple :

Le terme \og investissement \fg\ est utilisé dans deux acceptions
différentes :

À bientôt.

   Le Farfadet Spatial

Hors ligne

#38 Le 13/06/2010, à 03:37

mondai

Re : Enjoliver un fichier tex : vim ou emacs ?

@Luc Hermitte
http://code.google.com/p/lh-vim/source/ … c_core.vim

C'est qui qui me disait que mon .vimrc était trop long ? mdrrrr 843 lignes le tiens tongue

en tt cas merci de mettre ça sur internet, c'est très pratique pr moi.

Quand j'ai lu tes messages j'ai cru que t'étais un mec coincé mais en fait t'as aussi de l'humour lol

set showmode          " Show the current mode?  YEEEEEEEEESSSSSSSSSSS!

bon dès que je finis mon bizness avec ma configuration je modifierai la doc et je rajouterai ton site dans la doc.

Dernière modification par mondai (Le 13/06/2010, à 03:38)

Hors ligne

#39 Le 14/06/2010, à 15:29

Luc Hermitte

Re : Enjoliver un fichier tex : vim ou emacs ?

J'essaie surtout d'aller à l'essentiel quand je n'ai pas le temps de faire des réponses longues. Et si mon .vimrc ne fait 843 lignes, je compte dans les 76003 lignes de configuration pour vim répartie dans 364 fichiers. Ils ne sont certes pas tous de moi, même si les miens assurent un tiers de commentaires si je m'en tiens à ohloh.

Mon conseil n'était pas lié à une histoire  de maintenance, mais à une histoire que pour que les aspects de configuration de vim fonctionnent correctement, il faut absolument respecter les découpages en ftplugins, plugins d'indentation, etc. Sinon cela ne pourra jamais marcher correctement. J'insiste sur le "jamais".

Après, si je ne suis pas plus précis, c'est aussi parce que je n'ai plus joué avec LaTeX depuis assez longtemps, sans parler des fichiers de coloration ou d'indentation.

Hors ligne

#40 Le 24/10/2010, à 23:14

mondai

Re : Enjoliver un fichier tex : vim ou emacs ?

Salut,

Je me suis rappelé de ce fil où j'avais dit que je mettrai mon fichier de
configuration pour emacs, init.el. Cependant après j'ai appris un certain
nombre de choses, et finalement j'utilise Vim. Subjectivement, car je préfère, et
objectivement, car je trouve la complétion meilleure et plus pratique avec Vim.

J'ai fait un push de ma configuration de emacs que j'ai fais, assez récemment
sur github, vu que le init.el tout seul ne suffit pas pour faire marcher l'ensemble :

http://github.com/alexandre-k/repositor … ion_files/

Voici également le init.el ci-dessous (je ferai sans doute un post sur mon blog
pour expliquer l'ensemble) :

;Time-stamp: <2010-09-30 14:23:10 (freeman)>
;;##################################################################################################
;;##################################################################################################
 
                            ; LaTeX
                        
;;##################################################################################################

; ------------------------------------------------------------------------------------------------------------------
                        ;; load AucTeX etc
; ------------------------------------------------------------------------------------------------------------------
(require 'tex-site)
(require 'tex-style)
; ------------------------------------------------------------------------------------------------------------------
                    ; To turn on RefTeX Minor Mode for all LaTeX files, and other
; ------------------------------------------------------------------------------------------------------------------
(add-hook 'LaTeX-mode-hook 'turn-on-reftex)   ; with AUCTeX LaTeX mode
(add-hook 'reftex-load-hook 'imenu-add-menubar-index)
(add-hook 'reftex-mode-hook 'imenu-add-menubar-index)

(add-hook 'LaTeX-mode-hook
          '(lambda ()
             (setq TeX-open-quote "«~")
             (setq TeX-close-quote "~»")
             (auto-fill-mode t)
             ))
             
; ------------------------------------------------------------------------------------------------------------------
                    ; Smart quotes
; ------------------------------------------------------------------------------------------------------------------
(setq TeX-open-quote "<<")
(setq TeX-close-quote ">>")

; ------------------------------------------------------------------------------------------------------------------
                    ;LaTeX-math and other usefull stuff
; see http://www.emacswiki.org/emacs/AUCTeX
; ------------------------------------------------------------------------------------------------------------------
(add-hook 'LaTeX-mode-hook 'LaTeX-math-mode)
(add-hook 'LaTeX-mode-hook 'auto-fill-mode)
(add-hook 'LaTeX-mode-hook 'flyspell-mode)


;;; ------------------------ dictionnaire - correction orthographique -----------
;(setq-default ispell-program-name "hunspell")

;(add-hook 'text-mode-hook
;     (lambda ()
;        (flyspell-mode 1)
;        (ispell-change-dictionary "francais")
;        (turn-on-auto-fill)
;))
;--------------------------------------------------------------------------------------------------
                ; completion, style file, or multi-file stuff work
;--------------------------------------------------------------------------------------------------
(setq TeX-auto-save t)
(setq TeX-parse-self t)
;--------------------------------------------------------------------------------------------------
                    ;;Mode PDFLatex par défaut ou non
;--------------------------------------------------------------------------------------------------
(setq TeX-PDF-mode t); pour mettre par défaut décommenter cette ligne et commenter celle du dessous

;--------------------------------------------------------------------------------------------------
                    ;;Visualiseurs
;--------------------------------------------------------------------------------------------------
(setq TeX-output-view-style (quote (
      ("^pdf$" "." "evince %o")
      ("^ps$" "." "gv %o")
      ("^dvi$" "." "xdvi %o")
      )))
      (setq tex-dvi-view-command "xdvi")
(setq tex-dvi-print-command "dvips")
(setq tex-alt-dvi-print-command "dvips")

;------------------------------------------------------------------------------------------------
; Shortcut for compiling and viewing
;------------------------------------------------------------------------------------------------
(global-set-key [f4] 'XeLaTeX)

;--------------------------------------------------------------------------------------------------
;; Pour aller a la ligne automatiquement 
;--------------------------------------------------------------------------------------------------
(turn-on-auto-fill)

; ------------------------------------------------------------------------------------------------------------------
                    ; Autopairs
;see http://autopair.googlecode.com/svn/trunk/autopair.el
; ------------------------------------------------------------------------------------------------------------------
(add-to-list 'load-path "~/.emacs.d/lisp")
(require 'autopair)
(autopair-global-mode) ;; to enable in all buffers

;see http://www.emacswiki.org/emacs/AutoPairs#Discussion
; -------------------------------------------------
    (setq skeleton-pair t) ; enable pairing
    
; ------------------------------------------------------------------------------------------------------------------
                    ; master file
; ------------------------------------------------------------------------------------------------------------------
(setq-default TeX-master nil)
 TeX-master nil
 
;; ;;; ------------------------ Template -------------------------------
;; (setq load-path (cons (expand-file-name "~/.emacs.d/lisp")
;;                             load-path))
;; (require 'template)
;; (template-initialize)
;; ;;;; If you don't want to use yasnippet, look download the tarball here :
;; ;;;; voir http://emacs-template.sourceforge.net/

; ------------------------------------------------------------------------------------------------------------------
                    ; Wrapping the region in double quotes
; ------------------------------------------------------------------------------------------------------------------
    (defadvice TeX-insert-quote (around wrap-region activate)
      (cond
       (mark-active
        (let ((skeleton-end-newline nil))
          (skeleton-insert `(nil ,TeX-open-quote _ ,TeX-close-quote) -1)))
       ((looking-at (regexp-opt (list TeX-open-quote TeX-close-quote)))
        (forward-char (length TeX-open-quote)))
       (t
        ad-do-it)))
    (put 'TeX-insert-quote 'delete-selection nil)

; ------------------------------------------------------------------------------------------------------------------
                    ; Inserting and wrapping single quotes
; ------------------------------------------------------------------------------------------------------------------
    (defun TeX-insert-single-quote (arg)
      (interactive "p")
      (cond
       (mark-active
        (let ((skeleton-end-newline nil))
          (skeleton-insert
           `(nil ?` _ ?') -1)))
       ((or (looking-at "\\<")
            (looking-back "^\\|\\s-\\|`"))
        (insert "`"))
       (t
        (self-insert-command arg))))

    (add-hook 'LaTeX-mode-hook
              '(lambda ()
                 (local-set-key "'" 'TeX-insert-single-quote)))

; ------------------------------------------------------------------------------------------------------------------
 ;;set xetex mode in tex/latex
; ------------------------------------------------------------------------------------------------------------------
(add-hook 'LaTeX-mode-hook (lambda()
(add-to-list 'TeX-command-list '("XeLaTeX" "%`xelatex%(mode)%' %t" TeX-run-TeX nil t))
(setq TeX-command-default "XeLaTeX")
(setq TeX-save-query nil)
(setq TeX-show-compilation t)
))

;------------------------------------------------------------------------------------------------
                    ;Whizzy TeX
;------------------------------------------------------------------------------------------------

;; (setq my-toggle-whizzy-count 0)
;; (defun my-toggle-whizzy-mode ()
;;   (interactive)
;;   (if (= (mod my-toggle-whizzy-count 2) 0)
;;       (progn     
;;         (whizzytex-mode)
;;         (message "WhizzyTeX on"))
;;     (progn 
;;       (whizzy-mode-off)
;;       (kill-buffer (concat "*" (buffer-name) "*"))
;;       (message "WhizzyTeX off")))
;;   (setq my-toggle-whizzy-count (+ my-toggle-whizzy-count 1)))

;; (add-hook 'LaTeX-mode-hook
;;           (lambda ()
;;             (define-key LaTeX-mode-map (kbd "<f9>") 'my-toggle-whizzy-mode)))

;---------------------------------------------------------------------------------
                    ;Yasnippet
;; Auto completion / snippets
(add-to-list 'load-path "~/.emacs.d/lisp/yasnippet.el")
(require 'yasnippet)
(setq yas/root-directory "~/.emacs.d/snippets")
(yas/load-directory yas/root-directory)
(yas/global-mode)
(define-key global-map [f6] 'yas/expand)
(require 'dropdown-list)

;;       (setq yas/prompt-functions '(yas/dropdown-prompt
;;                                    yas/ido-prompt
;;                                    yas/completing-prompt))

;;##################################################################################################
;;                ;; GNUPlot
;;##################################################################################################           
  (add-to-list 'load-path "~/emacs.d/lisp/")
  (autoload 'gnuplot-mode "gnuplot" "gnuplot major mode" t)
  (autoload 'gnuplot-make-buffer "gnuplot" "open a buffer in gnuplot mode" t)

;; this line automatically causes all files with the .gp extension to
;; be loaded into gnuplot mode
  (setq auto-mode-alist (append '(("\\.gp$" . gnuplot-mode)) auto-mode-alist))

;; This line binds the function-9 key so that it opens a buffer into
;; gnuplot mode 
  (global-set-key [(f9)] 'gnuplot-make-buffer)

;;##################################################################################################
;;                 key board / input method settings
;;################################################################################################## 

;--------------------------------------------------------------------------------------------------
;; key board / input method settings
(setq locale-coding-system 'utf-8)
(set-terminal-coding-system 'utf-8)
(set-keyboard-coding-system 'utf-8)
(set-language-environment 'UTF-8)       ; prefer utf-8 for language settings
(setq read-quoted-char-radix 10)         ; use decimal, not octal
(load-library "iso-transl") ; for accent ^
;see http://tldp.org/HOWTO/Keyboard-and-Console-HOWTO-12.html
;http://www.docmirror.net/fr/linux/howto/hardware/Keyboard-and-Console-HOWTO/Keyboard-and-Console-HOWTO-8.html
;http://www.faqs.org/docs/Linux-HOWTO/Keyboard-and-Console-HOWTO.html
;(iso-accents-customize french)
;;; Pour le clavier
;(load-library "iso-ascii")
;(load-library "iso-insert")
;(iso-accents-mode)


;--------------------------------------------------------------------------------------------------
            ;Keyboard shortcuts
;--------------------------------------------------------------------------------------------------
(add-to-list 'load-path "~/.emacs.d/lisp/")
(require 'redo)
(define-key global-map (kbd "C-_") 'undo)
(define-key global-map (kbd "C-x C-_") 'redo)
;if you want to keep the C-w, M-w, and C-y original settings, there is a way is to bind cut, 
;copy and past keys by using the default X11 :
;http://www.emacswiki.org/emacs/CopyAndPaste
;; (global-set-key [(shift delete)] 'clipboard-kill-region)
;; (global-set-key [(control insert)] 'clipboard-kill-ring-save)
;; (global-set-key [(shift insert)] 'clipboard-yank)

;;######################################################################################################
                    ;; MENUS, BUFFERS...
;;######################################################################################################
;--------------------------------------------------------------------------------------------------
;;disable menu, toolbar, scrollbar
;--------------------------------------------------------------------------------------------------
(tool-bar-mode -1)
(toggle-scroll-bar -1)
;(set-scroll-bar-mode 'right)                                    ;;スクロールバーを右に表示
(menu-bar-mode 1)
;--------------------------------------------------------------------------------------------------
                ;menu avec les buffer dans une tabbar
                ; thanks to http://www.emacswiki.org/emacs/TabBarMode
;--------------------------------------------------------------------------------------------------
(add-to-list 'load-path "/usr/share/emacs/site-lisp/emhacks")
(require 'tabbar)
(tabbar-mode 1)

;; the following is taken from http://d.hatena.ne.jp/alfad/20100425/1272208744
;; 左に表示されるボタンを無効化
;-----------------------------------
;(setq tabbar-home-button-enabled "")
;(setq tabbar-scroll-left-button-enabled "")
;(setq tabbar-scroll-right-button-enabled "")
(setq tabbar-scroll-left-button-disabled "")
(setq tabbar-scroll-right-button-disabled "")

;; Firefoxライクなキーバインドに
;-----------------------------------
(global-set-key [(f8)] 'tabbar-forward)
(global-set-key [(f7)] 'tabbar-backward)

;all tabs is just one group
;-----------------------------------
 (setq tabbar-buffer-groups-function
          (lambda ()
            (list "All"))) ;; code by Peter Barabas

;--------------------------------------------------------------------------------------------------
                ; one more item n the menu for new files
;--------------------------------------------------------------------------------------------------

(define-key menu-bar-file-menu [new-file]
  '(menu-item "New..." find-file
          :enable (menu-bar-non-minibuffer-window-p)
          :help "Specify a new file's name, to edit the file"))

;--------------------------------------------------------------------------------------------------
                ;; A list of recent files
;--------------------------------------------------------------------------------------------------

(require 'recentf)
(setq recentf-exclude '("^/ftp.*" "^/ssh.*" "^/private.*" ))
(setq recentf-save-file "~/.emacs.d/recentf")
(recentf-mode 1)

;; GS-05/07/2006-12:15
;; http://www.emacswiki.org/cgi-bin/wiki/RecentFiles#toc6
(defun recentf-interactive-complete ()
  "find a file in the recently open file using iswitchb for completion"
  (interactive)
  (let* ((all-files recentf-list)
         (file-assoc-list (mapcar (lambda (x) (cons (file-name-nondirectory x) x)) all-files))
         (filename-list (remove-duplicates (mapcar 'car file-assoc-list) :test 'string=))
         (iswitchb-make-buflist-hook
          (lambda ()
            (setq iswitchb-temp-buflist filename-list)))
         (filename (iswitchb-read-buffer "Find Recent File: "))
         (result-list (delq nil (mapcar (lambda (x) (if (string= (car x) filename) (cdr x))) file-assoc-list)))
         (result-length (length result-list)))
         (find-file 
          (cond 
           ((= result-length 0) filename)
           ((= result-length 1) (car result-list))
           ( t
            (let ( (ido-make-buffer-list-hook
                     (lambda ()
                       (setq iswitchb-temp-buflist result-list))))
               (iswitchb-read-buffer (format "%d matches:" result-length))))
           ))))

;; to open recent files with keyboard
;;(global-set-key "\C-x\C-r" 'recentf-open-files-compl)
(global-set-key "\C-x\C-r" 'recentf-interactive-complete)

;--------------------------------------------------------------------------------------------------
                        ;; the minibuffer
;--------------------------------------------------------------------------------------------------
(setq
  enable-recursive-minibuffers nil         ;;  allow mb cmds in the mb
  max-mini-window-height .25             ;;  max 2 lines
  minibuffer-scroll-window nil
  resize-mini-windows nil)

;(icomplete-mode t)                       ;; completion in minibuffer
;; (setq 
;;   icomplete-prospects-height 1           ;; don't spam my minibuffer
;;   icomplete-compute-delay 0)             ;; don't wait
;; (require 'icomplete+ nil 'noerror)       ;; drew adams' extras

;;################################################################################################
                ;; FULLSCREEN : appuyer sur F11
                ;;thanks to http://www.emacswiki.org/emacs/FullScreen
;;################################################################################################

; -----------------------------------------------------------------------------------
                    ;F11 is for fullscreen
; -----------------------------------------------------------------------------------
    (defun fullscreen (&optional f)
      (interactive)
      (set-frame-parameter f 'fullscreen
                           (if (frame-parameter f 'fullscreen) nil 'fullboth)))

    (global-set-key [f11] 'fullscreen)

    (add-hook 'after-make-frame-functions 'fullscreen)
; -----------------------------------------------------------------------------------
                ;Send X Messages to the Window Manager
; -----------------------------------------------------------------------------------
 (defun fullscreen ()
       (interactive)
       (x-send-client-message nil 0 nil "_NET_WM_STATE" 32
                '(2 "_NET_WM_STATE_FULLSCREEN" 0)))

; -----------------------------------------------------------------------------------
            ; fullscreen mode                 
; --------------------------------------------------------------------------------------
                 (run-with-idle-timer 0.1 nil 'fullscreen)

; -----------------------------------------------------------------------------------------
            ;To maximize the window only, uncomment
; -----------------------------------------------------------------------------------------
                  (defun fullscreen (&optional f)
       (interactive)
       (x-send-client-message nil 0 nil "_NET_WM_STATE" 32
                 '(2 "_NET_WM_STATE_MAXIMIZED_VERT" 0))
       (x-send-client-message nil 0 nil "_NET_WM_STATE" 32
                 '(2 "_NET_WM_STATE_MAXIMIZED_HORZ" 0)))


;;#################################################################################################
;;                                     MOUSE, CURSOR
;;#################################################################################################

(mouse-wheel-mode t)
   (setq scroll-conservatively 10000)

;--------------------------------------------------------------------------------------------------
    ;; If you like to get a scroll one line at a time (less "jumpy" than defaults), uncomment
        ;;thanks to http://www.emacswiki.org/emacs/SmoothScrolling
;--------------------------------------------------------------------------------------------------    
  ;  (setq mouse-wheel-scroll-amount '(1 ((shift) . 1))) ;; one line at a time
    
   (setq mouse-wheel-progressive-speed nil) ;; don't accelerate scrolling
  ;     (setq mouse-wheel-progressive-speed true) ;;accelerate scrolling
    
   ;(setq mouse-wheel-follow-mouse 't) ;; scroll window under mouse
    
   ;(setq scroll-step 1) ;; keyboard scroll one line at a time
;(setq scroll-step 0) ;; keyboard don't scroll one line at a time

;--------------------------------------------------------------------------------------------------
         ; Molette de la souris
;--------------------------------------------------------------------------------------------------
    (defun up-slightly () (interactive) (scroll-up 5))
    (defun down-slightly () (interactive) (scroll-down 5))
    (global-set-key [mouse-4] 'down-slightly)
    (global-set-key [mouse-5] 'up-slightly)
    (defun up-one () (interactive) (scroll-up 1))
    (defun down-one () (interactive) (scroll-down 1))
    (global-set-key [S-mouse-4] 'down-one)
    (global-set-key [S-mouse-5] 'up-one)
    (defun up-a-lot () (interactive) (scroll-up))
    (defun down-a-lot () (interactive) (scroll-down))
    (global-set-key [C-mouse-4] 'down-a-lot)
    (global-set-key [C-mouse-5] 'up-a-lot)

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

;--------------------------------------------------------------------------------------------------
        ; 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)

;--------------------------------------------------------------------------------------------------
        ;; Use box cursor for overwrite-mode, and red cursor for quail active input.
        ;;thanks to http://www.jurta.org/en/emacs/dotemacs
;--------------------------------------------------------------------------------------------------
(defun my-change-cursor ()
  "Change cursor color and type depending on insertion mode and input method."
  (set-cursor-color
   (cond (current-input-method "red3") ; "AntiqueWhite4"
         ((eq (frame-parameter (selected-frame) 'background-mode) 'dark)
                               "DarkGrey")
         (t                    "black")))
  (setq default-cursor-type ;; set-cursor-type
   (cond (overwrite-mode       'box)
         (t                    'bar))))
(add-hook 'post-command-hook 'my-change-cursor)



;;###########################################################################################################
;;                         Title bar
;;###########################################################################################################

(setq frame-title-format '(buffer-file-name "Emacs: %b (%f)" "Emacs: %b")) ;CHEMIN COMPLET DANS LA BARRE DE TITRE

;--------------------------------------------------------------------------------------------------
;; de jolis noms pour les buffers sur un meme *nom* de fichier
;--------------------------------------------------------------------------------------------------
(require 'uniquify)
(setq uniquify-buffer-name-style 'post-forward-angle-brackets)

;;##################################################################################################
                    ;;Writing
;;##################################################################################################

;-------------------------------------------------------------------------------
        ;; Complétion automatique
        ;;Work in progress
;;see http://www.dr-qubit.org/emacs.php
;-------------------------------------------------------------------------------
;-----------------------------------------------------------------
 (abbrev-mode t) ; completion automatique
 (global-set-key (quote [tab]) (quote dabbrev-expand))

    (setq default-abbrev-mode t)
  (define-abbrev-table 'global-abbrev-table '(
     ("\.\.\." "\ldots" nil)
     ("letat" "l'État" nil)
     ("comeur" "Commission Européenne" t 4)
     ("coneur""Conseil Européen" nil)
     ))

;; ;------------------------------------------------------------------
;; ;to enable or disable completion-ui, comment or uncomment the following lines
(add-to-list 'load-path "~/.emacs.d/completion-ui/")
(require 'completion-ui)
(auto-completion-mode)
;(global-set-key [?\M-/] 'complete-dabbrev)

;; ;-------------------------------------------------------------------
;; ;auto-complete-mode

;; (setq dabbrev-case-replace nil)
;; (add-to-list 'load-path "~/.emacs.d/lisp/auto-complete-1.3")
;; (add-to-list  'load-path "~/.emacs.d/lisp/auto-complete-1.3/dict")
;; (require 'auto-complete-config)
;; (auto-complete-mode)
;; (ac-config-default)

;; ;(require 'auto-complete)
;; ;(setq ac-auto-start 1)
;; ;(require 'auto-complete-config)
;; (require 'popup)
;; ;(require 'fuzzy)
;; (global-auto-complete-mode t)
;; (setq ac-auto-start t)
;; ;(autoload 'auto-complete-mode t)

;; ;------------------------------------------------------------------------
;predictive
;; predictive install location
;;   (add-to-list 'load-path "~/.emacs.d/predictive/")
;;   ;; dictionary locations
;;   (add-to-list 'load-path "~/.emacs.d/predictive/latex/")
;;   (add-to-list 'load-path "~/.emacs.d/predictive/texinfo/")
;;   (add-to-list 'load-path "~/.emacs.d/predictive/html/")
;;   ;; load predictive package
;;   (require 'predictive)
;; (autoload 'predictive-mode "~/.emacs.d/predictive/predictive"
;;             "Turn on Predictive Completion Mode." t)


;-------------------------------------------------------------------------------
;;                  SUPPRIME TOUS LES ESPACES EN FIN DE LIGNE
;-------------------------------------------------------------------------------

(autoload 'nuke-trailing-whitespace "whitespace" nil t)

;-------------------------------------------------------------------------------
              ;Wrap Long Lines By Word Boundary
;-------------------------------------------------------------------------------
  (global-visual-line-mode 1) ; 1 for on, 0 for off.
  
;-------------------------------------------------------------------------------
;                   TEXT AND AUTO FILL MODE
;-------------------------------------------------------------------------------


(setq default-major-mode 'text-mode)
(add-hook 'text-mode-hook 'text-mode-hook-identify)
(add-hook 'text-mode-hook 'turn-on-auto-fill)
  
;-------------------------------------------------------------------------------
;; PARENTHESE MATCHING, PERMET DE VERIFIER AU FUR ET À MESURE DE LA FRAPPE QUE
;; L'ON FERME BIEN CE QUE L'ON OUVRE, AUSSI BIEN POUR LES PARENTHÈSES QUE LES
;; CROCHETS OU LES ACCOLADES.
;-------------------------------------------------------------------------------

(require 'paren)
(show-paren-mode 1)
(setq-default hilight-paren-expression t)
    
;-------------------------------------------------------------------------------
                ;;TIME STAMPS
                ;;thanks to http://www.djcbsoftware.nl/dot-emacs.html
;-------------------------------------------------------------------------------
;;Emacs permet d'insérer automatiquement des time stamps, typiquement
;;pour indiquer la date de dernière modification d'un fichier.
;;Pour utiliser les time stamps, indiquer dans les 8 premières lignes d'un fichier ceci :
;;Time-stamp: <>
(setq ;; when there's "Time-stamp: <>" in the first 10 lines of the file
  time-stamp-active t        ; do enable time-stamps
  time-stamp-line-limit 10   ; check first 10 buffer lines for Time-stamp: <>
  time-stamp-format "%04y-%02m-%02d %02H:%02M:%02S (%u)") ; date format
(add-hook 'write-file-hooks 'time-stamp) ; update when saving

;;################################################################################
            ;; File browser
;;################################################################################

(setq dired-ls-F-marks-symlinks t)
(defun my-dired-mode-init ()
  (hl-line-mode 1)
  (setq truncate-lines t))
(add-hook 'dired-mode-hook 'my-dired-mode-init)
;; Image viewer.
(when (require 'image-mode nil)
  (defun my-image-next-by-number ()
    (interactive)
    (let ((file-name (buffer-file-name))
      base num suffix
      num-width fmt)
      (unless (string-match
           "^\\(.*[^0-9-]\\)?\\(?:[0-9]+-\\)?\\([0-9]+\\)\\(\\.[^.]+\\)?$"
           file-name)
    (error "Improper file name"))
      (setq base (match-string 1 file-name))
      (setq num (match-string 2 file-name))
      (setq suffix (match-string 3 file-name))
      (setq num-width (length num))
      (setq fmt (format "%%s%%0%dd%%s" num-width))
      (setq num (1+ (string-to-number num)))
      (setq file-name (format fmt base num suffix))
      (unless (file-exists-p file-name)
    (setq fmt (format "%%s%%0%dd-*%%s" num-width))
    (setq file-name (format fmt base num suffix))
    (setq file-name (file-expand-wildcards file-name))
    (if file-name
        (setq file-name (car file-name))
      (error "No more files")))
      (find-alternate-file file-name)))
  (defun my-image-scroll-up-or-next-by-number ()
    (interactive)
    (let* ((image (image-get-display-property))
       (edges (window-inside-edges))
       (win-height (- (nth 3 edges) (nth 1 edges)))
       (img-height (ceiling (cdr (image-size image)))))
      (if (< (+ win-height (window-vscroll nil t))
         img-height)
      (image-scroll-up)
    (my-image-next-by-number))))
  (define-key image-mode-map (kbd "SPC")
    'my-image-scroll-up-or-next-by-number))

;-------------------------------------------------------------------------------
            ;To get a tree view
;-------------------------------------------------------------------------------
;(add-to-list 'load-path "/usr/share/emacs/site-lisp/emhacks/")
;(require 'dir-tree)

;------------------------------------------------------------------------------
              ;Deleting Files to Trash Folder
;-------------------------------------------------------------------------------
  ; deleting files goes to OS's trash folder
(setq delete-by-moving-to-trash t) ; "t" for true, "nil" for false

;-------------------------------------------------------------------------------
;;                    AFFICHAGE DES IMAGES ET FICHIERS COMPRESSÉS
;-------------------------------------------------------------------------------

(setq auto-image-file-mode t)
(setq auto-compression-mode t)

;;; view
;-------------------------------------------------------------------------------
(eval-after-load "view"
  '(progn
     ;; Shift-Space to scroll back.
     (define-key view-mode-map [?\S- ] 'View-scroll-page-backward)
     (define-key view-mode-map " " 'View-scroll-page-forward-set-page-size)
     (define-key view-mode-map "g" (lambda () (interactive) (revert-buffer nil t t)))
     (define-key view-mode-map "l" 'View-goto-line)
     (define-key view-mode-map [f2] 'toggle-truncate-lines)
     ;; (define-key view-mode-map [tab] 'other-window) ; used for next-ref
     ;; global: (define-key view-mode-map [(meta right)] 'find-file-at-point)
     (define-key view-mode-map [(meta left)]
       (lambda ()
         (interactive)
         ;; Go to the top to not store emacs-places.
         (goto-char (point-min))
         (View-quit)))
     (define-key view-mode-map [(meta down)]
       (lambda ()
         (interactive)
         (if (>= (window-end) (point-max))
             (goto-char (point-max))
           (View-scroll-page-forward-set-page-size))))
     (define-key view-mode-map [(meta up)]
       (lambda ()
         (interactive)
         (if (<= (window-start) (point-min))
             (goto-char (point-min))
           (View-scroll-page-backward-set-page-size))))
     ;; qv http://thread.gmane.org/gmane.emacs.devel/111117/focus=112357
     (defadvice View-scroll-line-forward (after my-View-scroll-line-forward activate)
       "Fix point position to be at the bottom line."
       (move-to-window-line -1)
       (beginning-of-line))
     ))

;;; doc-view
;-------------------------------------------------------------------------------
(eval-after-load "doc-view"
  '(progn
     ;; Shift-Space to scroll back.
     (define-key doc-view-mode-map [?\S- ] 'doc-view-scroll-down-or-previous-page)
     ))

;;; image
;-------------------------------------------------------------------------------
;; This is now in `image-dired-cmd-create-standard-thumbnail-command'
;; (used by `C-t C-t' in Dired).
(defun my-make-thumbnail (file)
  (let* ((image-file (concat "file://" (expand-file-name file)))
         (thumb-file (expand-file-name
                      (concat "~/.thumbnails/normal/" (md5 image-file) ".png")))
         (file-attrs (file-attributes file))
         (modif-time (float-time (nth 5 file-attrs))))
    (unless (file-exists-p thumb-file)
      (shell-command
       (mapconcat
        'identity
        (list
         "convert"
         (format "\"%s\"" file)
         ;; "-size 128x128"
         (format "-set \"Description\" \"Thumbnail of %s\"" image-file)
         (format "-set \"Software\" \"ImageMagick, GNU Emacs %s\"" emacs-version)
         (format "-set \"Thumb::URI\" \"%s\"" image-file)
         (format "-set \"Thumb::MTime\" \"%.0f\"" modif-time)
         "-set \"Thumb::Size\" \"%b\""
         "-set \"Thumb::Image::Width\" \"%w\""
         "-set \"Thumb::Image::Height\" \"%h\""
         "-set \"Thumb::Image::Mimetype\" \"image/jpeg\""
         "-resize 128x128" ;; "-resize 64x64"
         "+profile \"*\""
         "-type TrueColorMatte"
         ;; "-sharpen 11" ; TRY THIS
         (format "png:\"%s\"" thumb-file))
        " ")))
    thumb-file))

;;; thumbs
;-------------------------------------------------------------------------------
(defadvice thumbs-mode (after my-thumbs-mode activate)
  (toggle-truncate-lines -1))

;;; dired
;-------------------------------------------------------------------------------
(require 'dired-x)

;; HINT: the following expression is useful for `M-(' `dired-mark-sexp'
;; to mark files by their type:
;; (string-match "perl" (shell-command-to-string (concat "file " name)))

;; Uses editor/viewer info from /usr/bin/run-mailcap
(defun my-dired-run-find-file ()
  "My view file for dired."
  (interactive)
  (let* ((file (dired-get-filename)))
    (cond
     ((let* ((command
              (and (functionp 'mm-mime-info)
                   (mm-mime-info
                    (mm-extension-to-mime (file-name-extension file))))))
        (if (and command (stringp command))
            ;; always return `t' for `cond'
            (or (ignore (shell-command (concat (format command file) "&")))
                t))))
     ;; ((string-match "\\.html?$" file) (w3-open-local file))
     ((string-match "\\.html?$" file)
      (cond
       ((fboundp 'w3m-goto-url-new-session)
        (w3m-find-file-new-session file))
       ((fboundp 'browse-url)
        (browse-url file))))
     ((string-match "\\.elc?$" file)
      (load-file file))
     ((string-match "\\.info?$" file)
      (info file))
     (;; (or (string-match "\\.jpe?g$" file)
      ;;           (string-match "\\.gif$" file)
      ;;           (string-match "\\.pdf$" file))
      (let* ((file-list (list (dired-get-filename)))
             (command (dired-guess-default file-list)))
        (if (listp command)
            (setq command (car command)))
        (if command
            (shell-command
             (dired-shell-stuff-it command file-list nil 0)))))
     (t
      (message file)))))

(define-key dired-mode-map [(control return)] 'my-dired-run-find-file)

;; Add different directory sorting keys
;-------------------------------------------------------------------------------
(mapc (lambda (elt)
        (define-key dired-mode-map (car elt)
          `(lambda ()
            (interactive)
            (dired-sort-other (concat dired-listing-switches ,(cadr elt))))))
      '(([(control f3)]       ""     "by name")
        ([(control f4)]       " -X"  "by extension")
        ([(control f5)]       " -t"  "by date")
        ([(control f6)]       " -S"  "by size")
        ([(control shift f3)] " -r"  "by reverse name")
        ([(control shift f4)] " -rX" "by reverse extension")
        ([(control shift f5)] " -rt" "by reverse date")
        ([(control shift f6)] " -rS" "by reverse size")))
        
;; The following two bindings allow to open file for editing by [f4],
;; and return back to dired without killing the buffer.
;;--------------------------------------------------------------------------------
(define-key dired-mode-map [f3] 'dired-find-file) ;; 'dired-view-file
(define-key global-map [f3] 'dired-jump)

(define-key dired-mode-map [(shift f4)] 'dired-count-sizes)

;;##################################################################################################
                        ;highlighting
;;##################################################################################################
;;--------------------------------------------------------------------------------
                ;; Syntaxe highlighting pour tout
;;--------------------------------------------------------------------------------

(require 'font-lock)
(setq initial-major-mode
      (lambda ()
    (text-mode)
    (font-lock-mode)))
(setq font-lock-mode-maximum-decoration t
      font-lock-use-default-fonts t
      font-lock-use-default-colors t)
      
;;--------------------------------------------------------------------------------
                  ;; hl-line: highlight the current line 
                  ;;(thanks to http://www.djcbsoftware.nl/dot-emacs.html)
;;--------------------------------------------------------------------------------
(when (fboundp 'global-hl-line-mode)
  (global-hl-line-mode t)) ;; turn it on for all modes by default

;;--------------------------------------------------------------------------------
;;                                  ACTIVER LA COLORATION SYNTAXIQUE
;;--------------------------------------------------------------------------------
(global-font-lock-mode t)
(setq font-lock-maximum-decoration t)
(setq font-lock-maximum-size nil)
;;--------------------------------------------------------------------------------
;;                              SURLIGNAGE D'UNE RÉGION SÉLECTIONNÉE ET EFFACER
;;--------------------------------------------------------------------------------

(transient-mark-mode 1) ; highlight text selection
(delete-selection-mode 1) ; delete seleted text when typing

;;##################################################################################################
            ;;Sauvegardes, bookmarks, etc
;;##################################################################################################
;;--------------------------------------------------------------------------------
                ;; bookmarks
;;--------------------------------------------------------------------------------
(setq bookmark-default-file "~/.emacs.d/data/bookmarks" ;; bookmarks
  bookmark-save-flag 1)                            ;; autosave each change

;;--------------------------------------------------------------------------------
;;         saveplace: save location in file when saving files
;;--------------------------------------------------------------------------------
(setq save-place-file "~/.emacs.d/cache/saveplace")
(setq-default save-place t)            ;; activate it for all buffers
(require 'saveplace)                   ;; get the package

;;--------------------------------------------------------------------------------
;;         savehist: save some history
;;--------------------------------------------------------------------------------
(setq savehist-additional-variables    ;; also save...
  '(search ring regexp-search-ring)    ;; ... my search entries
  savehist-autosave-interval 60        ;; save every minute (default: 5 min)
  savehist-file "~/.emacs.d/cache/savehist")   ;; keep my home clean
(savehist-mode t)                      ;; do customization before activation


;;--------------------------------------------------------------------------------
            ;; Save/restore sessions on exit/startup.
;;--------------------------------------------------------------------------------

; (desktop-save-mode 1)

;;--------------------------------------------------------------------------------
 ;; POUR ENREGISTRER AUTOMATIQUEMENT LA POSITION DU CURSEUR QUAND ON QUITTE UN
;; FICHIER, ET Y RETOURNER AUTOMATIQUEMENT À LA RÉOUVERTURE
;;--------------------------------------------------------------------------------

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

;;--------------------------------------------------------------------------------
                ;; backups
;;--------------------------------------------------------------------------------
(setq make-backup-files t ;; do make backups
  backup-by-copying t     ;; and copy them here
  backup-directory-alist '(("." . "~/.emacs.d/backups")) 
  version-control t
  kept-new-versions 2
  kept-old-versions 5
  delete-old-versions t)

;;##################################################################################################
                    ;;APPEARENCE, etc
;;##################################################################################################
;--------------------------------------------------------------------------------------------------
;;                 Status bar
;--------------------------------------------------------------------------------------------------

(column-number-mode t) ;Affiche le numéro de ligne, de colonne
(line-number-mode t)    ;Affiche le numéro de colonne

(size-indication-mode t)                 ;; show file size (emacs 22+)

(display-time) ;POUR AVOIR L'HEURE DANS LA BARRE D'ETAT
(setq display-time-24hr-format t)  ;; Format 24 heures

;--------------------------------------------------------------------------------------------------
               ; folding mode
               ;work in progress \o/
;--------------------------------------------------------------------------------------------------

 (if (load "folding" 'nomessage 'noerror)
 (folding-mode-add-find-file-hook))
    
;--------------------------------------------------------------------------------------------------
               ; show hide
;--------------------------------------------------------------------------------------------------
    
 (defun toggle-selective-display (column)
      (interactive "P")
      (set-selective-display
       (or column
          (unless selective-display
             (1+ (current-column))))))
             
   (defun toggle-hiding (column)
      (interactive "P")
      (if hs-minor-mode
          (if (condition-case nil
                  (hs-toggle-hiding)
                (error t))
              (hs-show-all))
        (toggle-selective-display column)))
        
            (global-set-key (kbd "C-+") 'toggle-hiding)
    (global-set-key (kbd "C-\\") 'toggle-selective-display)
    
;--------------------------------------------------------------------------------------------------
                ;; tabulations
                ;; Comment changer la longueur des tabulations
                ;; pour un code écrit par
                ;; des sagouins.
;--------------------------------------------------------------------------------------------------

(defun tab4()
  "Les tabulations vaudront 4 espaces"
  (interactive "*")
  (setq tab-width 4)
)

(defun tab8()
  "Les tabulations vaudront 8 espaces"
  (interactive "*")
  (setq tab-width 8)
)

;--------------------------------------------------------------------------------------------------
                ;pour ne pas avoir de bandes verticales
                ;thanks to http://www.emacswiki.org/emacs/beginner.el
;--------------------------------------------------------------------------------------------------
;(set-fringe-mode 0)
;; don't show tiny scroll bar in echo area
;(set-window-scroll-bars (minibuffer-window) nil)
;--------------------------------------------------------------------------------------------------
                    ;Misc
;--------------------------------------------------------------------------------------------------

(setq visible-bell t)                                          ;;警告音を消す

;;################################################################################
                        ;;;  ESS
;;################################################################################

;; (require 'ess-site)
;; ;(require 'ess-eldoc)

;; (ess-add-MM-keys)   ;; notamment pour des "squelettes" de fonctions

;; (autoload 'ess-rdired "ess-rdired"
;;   "View *R* objects in a dire-like buffer." t)

;; (setq-default ess-ask-for-ess-directory t)   ;; demande le dossier de travail à chaque démarrage de R
;; (setq-default ess-directory "/media/ifremer/Analyses/R/")  ;; répertoire de travail proposé par défaut

;; (add-hook 'ess-mode-hook
;;      '(lambda ()
;;        (auto-fill-mode t)
;;        ;;(flyspell-mode t)
;;        (setq-default fill-column 100)
;;        )
;;      )

;; ;; Pour ajouter à la liste d'association les .Rhistory pour les traîter comme
;; ;; des fichiers sources R
;; (setq auto-mode-alist
;;       (append
;;        '(("\\.[rR]history\\'" . R-mode))
;;        auto-mode-alist))

;; (define-key ess-mode-map [f6] 'comint-dynamic-complete-filename)

;; ;; Montrer "au vol" les arguments de fonctions:

;; ;; ess-r-args-noargsmsg is printed, if no argument information could
;; ;; be found. You could set it to an empty string ("") for no message.
;; (setq ess-r-args-noargsmsg "No args found.")

;; ;; ess-r-args-show-as determines how (where) the information is
;; ;; displayed. Set it to "tooltip" for little tooltip windows or to
;; ;; nil (the default) which will use the echo area at the bottom of
;; ;; your Emacs frame.
;; ;; (setq ess-r-args-show-as "tooltip")

;; ;; ess-r-args-show-prefix is a string that is printed in front of the
;; ;; arguments list. The default ist "ARGS: ".
;; (setq ess-r-args-show-prefix "ARGS: ")

;; (defun Rnw-mode ()
;;   (require 'ess-noweb)
;;   (noweb-mode)
;;   (if (fboundp 'R-mode)
;;       (setq noweb-default-code-mode 'R-mode)))

;; (add-hook 'ess-mode-hook 'my-ess-options)
;; (setq-default inferior-R-args "--no-restore-history --no-save ")
;; (add-hook 'inferior-ess-mode-hook 'my-iess-keybindings)

;; (defun my-ess-options ()
;;   (ess-set-style 'C++)
;;   (column-number-mode t)
;;   (add-hook 'write-file-functions
;;         (lambda ()
;;           (nuke-trailing-whitespace)))
;;   (define-key ess-mode-map [(meta backspace)] 'backward-kill-word))

;; (defun my-iess-keybindings ()
;;   (define-key inferior-ess-mode-map [(control ?a)] 'comint-bol)
;;   (define-key inferior-ess-mode-map [home] 'comint-bol))

;;##################################################################################################

                ;;CUSTOMIZATION-FACE : FONT, COLOR
;; Modifications de l'apparence
;; font : aller dans Option --> Set default font ; pour sauvegarder : Option --> Save Options
;; color : pour tester les couleurs, aller dans le Menu --> Tools --> Color Themes
(add-to-list 'load-path "~/.emacs.d/color-theme-6.6.0/")
(require 'color-theme)
(eval-after-load "color-theme"
  '(progn
     (color-theme-initialize)
     (color-theme-andreas)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;    (require 'color-theme)
  ;  (color-theme-initialize)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;    (color-theme-andreas)
;; pour color theme voir aussi dans dans Option --> Customize emacs --> Browse customization groups --> Group "Faces" --> Group "Color Theme" 
;; pour LaTeX :
;; - \emph --> font-latex-italic-face
;; - \footnote --> font-lock-constant-face
;; - commandes (\emph, \textsc) --> font-lock-keyword-face

;;##################################################################################################

;--------------------------------------------------------------------------------------------------
                ;Default font
                ;thanks to http://www.emacswiki.org/emacs/XftGnuEmacs
;--------------------------------------------------------------------------------------------------
;; To me, the best fonts are as follow ; modify if you prefer Bitstream or another font :

;(set-default-font "Deja Vu Sans Mono 10")

;--------------------------------------------------------------------------------------------------
(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.
 '(blink-cursor-mode nil)
 '(column-number-mode t)
 '(display-time-mode t)
 '(show-paren-mode t)
 '(size-indication-mode t))

;;##################################################################################################
;;                MISCELLANEOUS
;;##################################################################################################
;--------------------------------------------------------------------------------------------------
                ;; do not show the startup message and other stuff
                ;; at http://www.djcbsoftware.nl/dot-emacs.html
;--------------------------------------------------------------------------------------------------

(put 'narrow-to-region 'disabled nil)    ;; enable...
(put 'erase-buffer 'disabled nil)        ;; ... useful things
(file-name-shadow-mode t)                ;; be smart about filenames in mbuf

(setq inhibit-startup-message t          ;; don't show ...    
  inhibit-startup-echo-area-message t)   ;; ... startup messages
  
;--------------------------------------------------------------------------------------------------
;;                   POUR NE PAS AVOIR À TAPER EN ENTIER LA RÉPONSE YES/NO
;--------------------------------------------------------------------------------------------------

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

;--------------------------------------------------------------------------------------------------
                    ;; Fichiers annexes dans ~/.emacs.d/lisp
;--------------------------------------------------------------------------------------------------
;;stuff in separate files;; maybe use autoload?

;;inclusion de la gestion des couleurs
;(require 'couleurs nil 'noerror)
;----------------------------------------
;;inclusion du calendrier
(add-to-list 'load-path "~/.emacs.d/lisp/")
;(require 'calendrier nil 'noerror)
;----------------------------------------
;;afficher les numéros de ligne
(load-file "~/.emacs.d/lisp/line-num.el")
;(and (< emacs-major-version 20) (eval-when-compile (require 'cl)))
;----------------------------------------
;(add-to-list 'load-path "~/.emacs.d/lisp/linum.el")
;(require 'linum)
;(autoload 'linum-mode "linum")

;display line numbers in margin (fringe). Emacs 23 only.
;(global-linum-mode 1) ; always show line numbers

;--------------------------------------------------------------------------------------------------
;;                                            THUMBS-MODE
;--------------------------------------------------------------------------------------------------
 (autoload 'thumbs "thumbs" "Preview images in a directory." t)
  
;--------------------------------------------------------------------------------------------------
                    ;Search and case sensitivity
;--------------------------------------------------------------------------------------------------

; (setq case-fold-search nil) ; make searches case sensitive
 (setq case-fold-search t) ; make searches case insensitive
 
;--------------------------------------------------------------------------------------------------
            ;; Switch ispell dictionary locally.
;--------------------------------------------------------------------------------------------------
        ;;; Mode Ispell 
;; (require 'ispell)
;;   (setq ispell-dictionary "francais")

;; (global-set-key (kbd "C-c d e")
;;                 (lambda () (interactive)
;;                   (ispell-change-dictionary "english")))
;; (global-set-key (kbd "C-c d f")
;;                 (lambda () (interactive)
;;                   (ispell-change-dictionary "francais")))
  
;--------------------------------------------------------------------------------------------------
                 ; Comment rafraîchir un fichier dans .emacs lorsqu'il
                 ; a été modifié par un autre programme ?
                 ; thanks to http://www.emacswiki.org/emacs/RevertBuffer
;--------------------------------------------------------------------------------------------------
 
  (global-auto-revert-mode 1)
  
 ;-----------------------------------------------------------
 ; a function to revert all buffers :
 ;-----------------------------------------------------------
   (defun revert-all-buffers ()
   "Refreshes all open buffers from their respective files"
   (interactive)
   (let* ((list (buffer-list))
          (buffer (car list)))
     (while buffer
       (when (buffer-file-name buffer)
         (progn
           (set-buffer buffer)
           (revert-buffer t t t)))
       (setq list (cdr list))
       (setq buffer (car list))))
  (message "Refreshing open files"))
  
;--------------------------------------------------------------------------------------------------
(defun my-info-refresh (&optional arg)
  "Display some useful information in the echo area instead of the mode line.
With prefix arg, insert the current timestamp to the current buffer."

;; §§ WORK IN PROGRESS §§ doesn't work !

;--------------------------------------------------------------------------------------------------
  (interactive "P")
  (cond
   ((equal arg '(4))  ; C-u f5
    (insert (format-time-string "%Y%m%d" (current-time))))
   ((equal arg '(16)) ; C-u C-u f5
    (insert (format-time-string "%Y-%m-%d" (current-time))))
   (t (message "%s"
               (concat
                (format-time-string "%Y-%m-%d %H:%M:%S %z" (current-time)) ;; ISO
                " "
                (aref calendar-day-abbrev-array (nth 6 (decode-time (current-time))))
                " : "
                (or (buffer-file-name) default-directory))))))

;(define-key my-map     [f5]  'my-info-refresh)
;(define-key global-map [f5]  'my-info-refresh)

;; open Word files with antiword
(autoload 'no-word "no-word" "word to txt")
(add-to-list 'auto-mode-alist '("\\.doc\\'" . no-word))
(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 (:inherit nil :stipple nil :background "white" :foreground "black" :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight normal :height 98 :width normal :foundry "unknown" :family "DejaVu Sans Mono")))))

Cependant maintenant que j'ai un peu plus d'expérience, j'ai un peu honte de
montrer ce que j'ai fais avec emacs (d'autant plus que vu que je n'utilise plus
emacs, c'est resté le bordel).

Toujours est-il que je recommande d'utiliser Vim. Plus j'essaie d'automatiser les
tâches que je fais, plus je me rends compte à quel point c'est un excellent
éditeur de texte, et plus j'impressionne, au passage, les gens qui regardent
mon ordi et ma vitesse de frappe avec toutes les abbréviations que j'ai fais
et l'excellente auto-complétion.

Bonne soirée,
mondai

Dernière modification par mondai (Le 24/10/2010, à 23:16)

Hors ligne

#41 Le 24/10/2010, à 23:56

tshirtman

Re : Enjoliver un fichier tex : vim ou emacs ?

Et les configs que t'as fais pour vim? vu que je suis utilisateur vim, ça m'intéresse ^^.

Hors ligne

#42 Le 25/10/2010, à 09:33

HP

Re : Enjoliver un fichier tex : vim ou emacs ?

Airballman a écrit :

Pour info, je code sous Vim en Python wink et les onglets sésuppère!

Faut juste se faire au Alt+Tab…
Perso, avant, sous Mac OS X, j'utilisais Aquamacs (capture) qui avait une barre d'onglets… j'imaginais difficilement m'en passer… bé, sous GNU/Linux, un WM quelconque et un panel tout aussi quelconque (openbox et xfce4-pnael, chez moi), je ne suis pas trop perdu sans onglets… parce que j'utilise de plus en plus intensivement Alt+Tab… alors, les onglets, réelle nécessité ?


cat /dev/urandom >/dev/null 2>&1 #github

Hors ligne

#43 Le 25/10/2010, à 09:39

tshirtman

Re : Enjoliver un fichier tex : vim ou emacs ?

ben plus t'as de façons différentes de séparer et acceder a tes programmes, plus vite tu peux acceder à chacuns, entre les raccourcis de mon WM, ceux de screen, mes onglets/splits de vim, il arrive que je me perde un peu, mais quand j'ai organisé un environnement de travail, les raccourcis pour acceder instantanément à chaque écran sont dans les doigts, et on peut être vachement efficace.

j'ai bindé ctrl + -> et ctrl+ <- pour passer d'un onglet à l'autre dans vim, et c'est bien pratique.

Hors ligne

#44 Le 25/10/2010, à 20:23

mondai

Re : Enjoliver un fichier tex : vim ou emacs ?

Salut,

Tshirtman a écrit :

Et les configs que t'as fais pour vim? vu que je suis utilisateur vim, ça m'intéresse ^^.

Pas de problème, mais là ma configuration de vim pour \LaTeX est en
reconstruction en quelque sorte.

Sur github j'avais fais un push de ma configuration :

Et sur mon blog j'avais fais une description rapide et l'utilisation que j'en
faisais :
installing-and-setting-vim/
Et :
writing-latex-files-with-gvim/

Mais en pratique, plus j'en apprends, plus j'utilise Vim, et plus ma
configuration évolue. Par exemple, pour utiliser mes abbréviations sur le forum
j'utilise Vim pour écrire, et j'ai rajouté les balises dans la partie mapping de
mon vimrc (que j'ai divisé en plusieurs parties) pour les mettre
automatiquement.

C'est vraiment juste un exemple, mais ce que je veux dire c'est que tous les
jours, je change des trucs, et j'en rajoute d'autres (bon là je suis occupé avec
tikz et avec mes études, donc en fait je rajoute plus que je change). Ma
configuration de Vim a globalement peu changé par rapport à celle que j'ai mis
sur Github, mais donc ma configuration pour \LaTeX est en quelque sorte vouée à
changer beaucoup (d'autant plus que là je n'ai pas encore configuré le
nécessaire pour compiler). Si elle t'intéresse quand même, la voici :


" "========================================================================="
" GENERAL SETTINGS
" "========================================================================="
"{{{
"let g:autoclose = 1

"setlocal efm+=%E%f:%l:\ %m

"To jump from a section to another one
map <silent> ]s :/\\\(sub\)\{,2}section\s*{<CR> :noh<CR>
map <silent> [s :?\\\(sub\)\{,2}section\s*{<CR> :noh<CR>

"---------------------------------
"Enhanced Vim formatting of LaTeX files
"---------------------------------
"map \gq ?^$\\|^\s*\(\\begin\\|\\end\\|\\label\\|\\documentclass\\|\\usepackage\\|\\paragraph\\item\)?1<CR>gq//+1<CR>
"omap lp ?^$\\|^\s*\(\\begin\\|\\end\\|\\label\)?1<CR>//-1<CR>.<CR>
map \gq ?^$\\|^\s*\(\\begin\\|\\end\\|\\item\\|\\label\)?1<CR>gq//-1<CR>
omap lp ?^$\\|^\s*\(\\begin\\|\\end\\|\\item\\|\\label\)?1<CR>//-1<CR>.<CR>

"---------------------
"Dictionaries
autocmd Filetype tex,latex :set dictionary=~/.vim/dictionaries/dictionary,/home/linux/.vim/spell
"}}}
" "========================================================================="
" BASIC SETTINGS FOR LATEXBOX
" "========================================================================="
"{{{
let g:LatexBox_viewer = 'evince'
"let g:LatexBox_latexmk_options = '-pdf -e "$pdflatex="xelatex --interaction=nonstopmode --synctex=1 %O %S""'
"let g:LatexBox_output_type = 'dvi' Default: 'pdf'
"let g:LatexBox_split_width = '30'  "for table of content. Default: 30

"map <silent> <Leader>ls :silent !/usr/bin/evince\ <C-R>=line('.')<CR> "<C-R>=LatexBox_GetOutputFile()<CR>" "%:p" <CR>

"$pdflatex = 'xepdflatex.sh %S';
let g:LatexBox_latexmk_options = '$pdflatex = "xelatex -synctex=1 %O %S"'
"$pdf_previewer = "start xpdf -remote %R %O %S";
"$pdf_update_method = 4;
"$pdf_update_command = "xpdf -remote %R -reload";

"    An attempt to make GVim behave like TeXWorks
" save file whenever cursor moves
"function! Update_if_possible()
    "if filewritable(bufname("%"))
        "update
    "endif
"endfunction
"au CursorMoved * call Update_if_possible()
"au CursorMovedI * call Update_if_possible()
"}}}
" "========================================================================="
" BASIC SETTINGS FOR LATEXSUITE
" "========================================================================="
"        {{{
"http://vim-latex.sourceforge.net/documentation/latex-suite/recommended-settings.html
"-------------------------------------------------------------------------

" IMPORTANT: win32 users will need to have 'shellslash' set so that latex
" can be called correctly.
"set shellslash

" IMPORTANT: grep will sometimes skip displaying the file name if you
" search in a singe file. This will confuse Latex-Suite. Set your grep
" program to always generate a file-name.
"set grepprg=grep\ -nH\ $*

"let g:Tex_SmartKeyQuote = 1
"let g:Tex_ViewRule_dvi = 'xdvi'
"let g:Tex_ViewRule_ps  = 'gv'
"let g:Tex_ViewRule_pdf = 'evince'

"let g:Tex_DefaultTargetFormat='pdf'
"let g:Tex_CompileRule_pdf='/usr/local/texlive/2010/bin/i386-linux/xelatex $*'
"}}}
" "========================================================================="
" MAPPING
" "========================================================================="
"{{{ Miscellanous
"--------------------------------
"fixing of é letter for Vim with LaTeXsuite. I have commented it since I use LaTeXBox
"imap <buffer> <leader>it <Plug>Tex_InsertItemOnThisLine
"imap <C-b> <Plug>Tex_MathBF
"imap <C-c> <Plug>Tex_MathCal
"imap <C-l> <Plug>Tex_LeftRight

"---------------------------------------
"Another shortcut for placeholders.
"The default one is ctrl+j, really 
"annoying. Pressing tab is easier
"imap <s-tab> <Plug>IMAP_JumpForward

"---------------------------------------
"useful imaps
imap <buffer> ,ja {\ja 
"the above imap is intended to work with 
"my setup for japanese in my templates compiled
"with XeLaTeX. For more details, look at my
"blog : [url]http://alexkrispin.wordpress.com[/url]/
imap <buffer> ... \ldots
imap <buffer> ,vd \vdots
imap <buffer> ,math \[<CR><ESC>2hi<CR>\]
imap <buffer> ,re \mathbb{R}
imap <buffer> ,resu \mathbb{R}\^{}<ESC>i
imap <buffer> ,_ _{}<ESC>i
imap <buffer> ,su ^{}<ESC>i
imap <buffer> ,fra \frac{}{<++>}<ESC>6hi
imap <buffer> " << >><ESC>i
"---------------------------------------
"With XeLaTeX, these imaps are no longer
"required since you compile with
"unicode. In case you use pdfLaTeX to 
"compile, you may consider to enable the 
"following :
"imap <buffer> « \og
"imap <buffer> » \fg
"imap <buffer> € \EUR
"imap <buffer>~ $\sim\ 
"imap <buffer> " \textquotedblleft 
"imap <buffer> ¢ \textquotedblright\ 

"--------------------------------------
"If you have a french keyboard, this setting
"will let you easily put, let say `bf.
"Instead of inserting `bf in normal mode
"you will just have to insert ,bf (therefore,
"no need of the Alt Gr key)
"vmap <buffer> <silent>, `
"}}}
"{{{ General mapping
" Caractères gras
" TeX, LaTeX
    imap ,tex \TeX{}
    imap ,la \LaTeX{}

    " Euro
    imap ,eu \euro{}

    " Insertion fraction
    imap ,fr \dfrac{}{}<ESC>2hi
    imap ,tfr \tfrac{}{}<ESC>2hi

    " Taille math standard
    imap ,dst \displaystyle{}<ESC>i
    vmap ,dst s\displaystyle{<ESC>pa}

    " Insertion d'une figure
    imap ,igr \includegraphics{}<ESC>i
    vmap ,igr s\includegraphics{<ESC>pa}
 
    imap ,ppr \parpic[r]{\includegraphics{}}<ESC>hi
    imap ,ppl \parpic[l]{\includegraphics{}}<ESC>hi
 
    vmap ,ppr s\parpic[r]{\includegraphics{<ESC>pa}}
    vmap ,ppl s\parpic[l]{\includegraphics{<ESC>pa}}
 
    imap ,fig \begin{figure}<CR>\end{figure}<ESC>O
    vmap ,fig S\begin{figure}<CR>\end{figure}<ESC>P
 
    imap ,wf \begin{wrapfigure}{}{}<CR>\end{wrapfigure}<ESC>O\includegraphics{}<ESC>i
    """""vmap ,wf S\begin{wrapfigure}{}{}<CR>\end{wrapfigure}<ESC>\includegraphics{}P
    
    " Table des matières
    imap ,toc \tableofcontents

    " (Sous-(sous-)Section numérotée
    imap ,s \section{}<ESC>i
    imap ,ss \subsection{}<ESC>i
    imap ,sss \subsubsection{}<ESC>i
    vmap ,s s\section{<ESC>pa}
    vmap ,ss s\subsection{<ESC>pa}
    vmap ,sss s\subsubsection{<ESC>pa}

    " (Sous-)Section non-numérotée
    imap ,s* \section*{}<ESC>i
    imap ,ss* \subsection*{}<ESC>i
    imap ,sss* \subsubsection*{}<ESC>i
    vmap ,s* s\section*{<ESC>pa}
    vmap ,ss* s\subsection*{<ESC>pa}
    vmap ,sss* s\subsubsection*{<ESC>pa}

    " Présentations LaTeX-Beamer
    imap ,un \uncover<><ESC>i
    imap ,on \only<><ESC>i
    imap ,fm \begin{frame}<CR>\end{frame}<ESC>O
 
    imap ,ft \frametitle{}<ESC>i
    imap ,al \alert{}<ESC>i
    
    " Marques de modifications
    imap ,chb \begin{changebar}<CR>\end{changebar}<ESC>O
    vmap ,chb S\begin{changebar}<CR>\end{changebar}<ESC>P
    
    " Environnement quelconque
    imap ,env \begin{ENV}<CR>\end{ENV}<ESC>O
    vmap ,env S\begin{ENV}<CR>\end{ENV}<ESC>P

    " Retour ou saut de ligne
    imap ,cr \\ <CR>

    " Retour à la ligne justifié
    imap ,lb \linebreak 

    " Retour à la ligne simple
    imap ,nl \newline

    " Saut de page
    imap ,pb \pagebreak

    " Changement de colonne
    imap ,cb \columnbreak
    
    " Gros saut de ligne
    imap ,bs <CR>\bigskip<CR>
    
    " Ligatures
    imap ,oe \oe{}
    
    " Mode maths en ligne
    imap ,$ $$<ESC>i
    vmap ,$ s$<ESC>pa$

    " Mode maths centré
    imap ,$$ \[<CR>\]<ESC>O
    vmap ,$$ S\[<CR>\]<ESC>P

    " Texte normal en mode maths
    imap ,rm \textrm{}<ESC>i
    
    " Racine carrée
    imap ,rc \sqrt{}<ESC>i
    vmap ,rc s\sqrt{<ESC>pa}

    " Pi
    imap ,pi \pi
    imap ,Pi \Pi

    " Angles et trigo
    imap ,wh \widehat{}<ESC>i
    imap _c \cos
    imap _s \sin
    imap _t \tan

    " Flèche fonction 
    imap ,lm \longmapsto<ESC>a

    " Signe multiplié
    imap ,* \times
    
    " Signé divisé
    imap ,/ \div
    
    " Centrage
    imap ,c \begin{center}<CR>\end{center}<ESC>O
    vmap ,c S\begin{center}<CR>\end{center}<ESC>P

    " Frame
    imap ,frm \frame<CR>}<ESC>O
    vmap ,frm S\frame{<CR>}<ESC>P
    
    " Minipage
    imap ,mp \begin{minipage}[t]{}<CR>\end{minipage}<ESC>O
    vmap ,mp S\begin{minipage}[t]{}<CR>\end{minipage}<ESC>P
    
    " Double-colonnage
    imap ,dc \begin{multicols}{2}<CR>\end{multicols}<ESC>O
    vmap ,dc S\begin{multicols}{2}<CR>\end{multicols}<ESC>P
    
    " Caractères machine à écrire
    imap ,tt \texttt{}<ESC>i
    vmap ,tt s\texttt{<ESC>pa}

    " Caractères gras
    imap ,bf \textbf{}<ESC>i
    vmap ,bf s\textbf{}<ESC>Pi

    " Paragraphe
    imap ,pa \paragraph{}<ESC>i
    vmap ,pa s\paragraph{}<ESC>Pi

 
    " Soulignement
    imap ,_ \underline{}<ESC>i
    vmap ,_ s\underline{<ESC>pa}
    
    " Ligne supérieure
    imap ,ol \overline{}<ESC>i
    vmap ,ol s\overline{<ESC>pa}
    
    " Caractères penchés
    imap ,sl \textsl{}<ESC>i
    vmap ,sl s\textsl{<ESC>pa}
 
    imap ,sls {\slshape<CR>}<ESC>O
    vmap ,sls S{\slshape<CR>}<ESC>P
    
    " Caractères italiques
    imap ,i \textit{}<ESC>i
    vmap ,i s\textit{<ESC>pa}

    imap ,em \emph{}<ESC>i
    vmap ,em s\emph{}<ESC>pa}

    imap ,is {\itshape<CR>}<ESC>O
    vmap ,is S{\itshape<CR>}<ESC>P
    
    " Petites capitales
    imap ,sc \textsc{}<ESC>i
    vmap ,sc s\textsc{<ESC>pa}
    
    " Caligraphiques math
    imap ,mc \mathscr{}<ESC>i
    vmap ,mc s\mathscr{<ESC>pa}

    " Ensembles math
    imap ,mb \mathbb{}<ESC>i
    vmap ,mb s\mathbb{<ESC>pa}

    " Ensembles
    imap ,bb \mathbb{}<ESC>i
    vmap ,bb s\mathbb{<ESC>pa}
    
    " Verbatim
    imap ,vb+ \verb++<ESC>i
    vmap ,vb+ s\verb+<ESC>pa+
 
    imap ,vbt \begin{verbatim}<CR>\end{verbatim}<ESC>O
    vmap ,vbt S\begin{verbatim}<CR>\end{verbatim}<ESC>P
        
    " Vecteur
    imap ,v \overrightarrow{}<ESC>i
    vmap ,v s\overrightarrow{<ESC>pa}

    " Logarithmes, exponentielles
    imap ,ln \ln{}<ESC>i
    imap ,exp \exp{}<ESC>i
 
    vmap ,ln s\ln{<ESC>pa}
    vmap ,exp s\exp{<ESC>pa}

    " Infini
    imap ,inf \infty{}

    " Fantôme
    imap ,ph \phantom{}<ESC>i
    vmap ,ph s\phantom{<ESC>pa}

    " Insertion tableau
    imap ,tab \begin{tabular}[t]{}<CR>\end{tabular}<ESC>k$i
    imap ,tabc \begin{tabular}[c]{}<CR>\end{tabular}<ESC>k$i
    imap ,hl \hline
 
    imap ,ar \begin{array}[t]{rcl}<CR>\end{array}<ESC>O
    imap ,eqn \begin{eqnarray*}<CR>\end{eqnarray*}<ESC>O
 
    imap ,sy \left\lbrace{}<CR>\begin{array}{rcl}<CR>\end{array}\right.<ESC>O
 
    vmap ,tab S\begin{tabular}[t]{}<CR>\end{tabular}<ESC>P

    " = en tableau math
    imap ,& &<SPACE>=<SPACE>&<SPACE>
    imap ,ou &<SPACE>\textrm{ ou }<SPACE>&<SPACE>

    " Interligne tableaux
    imap ,ast \renewcommand{\arraystretch}{1.8}

    " Accolades systèmes
    imap ,{ \left\lbrace{}
    imap ,. \right.
    
    " Liste
    imap ,ite \begin{itemize}<CR>\end{itemize}<ESC>O\item<SPACE>
    vmap ,ite S\begin{itemize}<CR>\end{itemize}<ESC>P
 
    imap ,it \item
    
    " Enumeration
    imap ,en \begin{enumerate}[1°)]<CR>\end{enumerate}<ESC>O\item<SPACE>
    vmap ,en S\begin{enumerate}[1°)]<CR>\end{enumerate}<ESC>P
    
    " Description
    imap ,des \begin{description}<CR>\end{description}<ESC>O\item[]<ESC>i
    imap ,itd \item[]<ESC>i
    
    " Au fer à droite
    imap ,r \begin{flushright}<CR>\end{flushright}<ESC>O
    vmap ,r S\begin{flushright}<CR>\end{flushright}<ESC>P
    
    " Au fer à gauche
    imap ,l \begin{flushleft}<CR>\end{flushleft}<ESC>O
    vmap ,l S\begin{flushleft}<CR>\end{flushleft}<ESC>P

    " Alinéa
    imap ,ind \indent{}

    " Pas d'alinéa
    imap ,noi \noindent{}

    " Largeur de texte
    imap ,tw \textwidth

    " Espaces supplémentaires
    imap ,, \,
    imap ,; \;
    imap ,q \quad
    imap ,qq \qquad

    " Espacement horizontal ou vertical
    imap ,hs \hspace{}<ESC>i
    imap ,vs \vspace{}<ESC>i

    " Remplissage horizontal ou vertical
    imap ,hf \hfill
    imap ,vf \vfill
    
 
    " Parenthèses
    imap ,( \left(
    imap ,) \right)
    imap ,() \left(   \right)<ESC>8hi

    " Crochets
    imap ,[ \left[
    imap ,] \right]
    imap ,dcr \left[   \right]<ESC>8hi
    
 
    " Rien à droite
    imap ,. \right.

    " Environ égal
    imap ,= \simeq

    " Différent
    imap ,n= \not=
    
    " Inégalités
    imap ,< \leqslant{}
    imap ,> \geqslant{}

    " Équivalences
    imap ,eq \Longleftrightarrow{}

    " Nombres barrés
    imap ,ca \cancel{}<ESC>i
    vmap ,ca s\cancel{}<ESC>Pa

    " Boîtes
    imap ,fb \fbox{}<ESC>i
    vmap ,fb c\fbox{}<ESC>PA

    " Numéros
    imap ,no \no{}<ESC>i
    imap ,No \No{}<ESC>i
    imap ,e \ieme{}<ESC>i
    imap ,er 1\ier{}

    " Renvois
    imap ,fn \,\footnote{}<ESC>i

    " Liens
    imap ,url \url{}<ESC>i
    imap ,hr \href{}{}<ESC>2hi
 
    vmap ,url s\url{<ESC>pa}
    vmap ,hr s\href{<ESC>pa}{} "}}}
" "========================================================================="
"ABBREVIATIONS
" "========================================================================="
"            {{{
"------------------------------
"General {{{
iab ds dans
iab bcp beaucoup
iab mm même
iab dc donc
iab Ds Dans
iab Dc Donc
iab Qqn Quelqu'un
iab qqn quelqu'un
iab Tjr Toujours
iab qqc quelque chose
iab pol politique
iab leurope l'Europe
iab tv télévision
iab ceca CECA
iab ue Union Européenne
iab CE Commission Européenne
iab AL Amérique Latine
iab etat État
iab letat l'État
iab socio sociologie
iab socioq sociologique
iab éco économie
iab écoq économique
iab math mathématique
iab xelatex \XeLaTeX
iab latex \LaTeX
iab ak Alexandre Krispin
iab tt tout
iab tte toute
iab ts tous
iab ttes toutes
iab kil qu'il
iab ke que
iab ki qui
iab prin principe
iab tjr toujours
iab doc document
iab chak chaque
iab pr pour
iab qq quelque
iab cest c'est
iab Cest C'est
iab cad c'est-à-dire
iab qqcq quelconque
iab Cad C'est-à-dire
iab pk pourquoi
iab kan quand
iab juska jusqu'à
iab Pr Pour
iab pdt pendant
iab Pk Pourquoi
iab puisk puisque
iab Kel Quel
iab Kelle Quelle
iab nest n'est
iab Quece Qu'est-ce que
iab lakel laquelle
iab lekel lequel
iab Tt Tout
iab kel quel
iab kell quelle
iab kom comme
iab Kan Quand
iab Ke Que
iab puiskil puisqu'il
"}}}
"------------------------------
"Politics {{{
iab etatn État-nation
iab letatn l'État-nation
iab écopol économie politique
iab apriori \emph{a priori}
iab exante \emph{ex ante}
iab facultyeco Sciences économiques \textendash\ gestion
iab facultypol Sciences politiques
iab degreeeco Licence 2\ieme\ année
iab degreepol Licence 3\ieme\ année
iab volgé volonté générale
iab rousseau Rousseau
iab anglo anglosaxon
iab kestion question
iab legalite l'égalité
iab neolib néo-libéral
"}}}
"------------------------------
" Sociologie {{{
iab gender \emph{gender}"

"}}}
"------------------------------
"mathematics {{{
iab coord coordonnées
iab déf définit
iab dét déterminant
iab const constante
"}}}
""-----------------------------
"comptabilité {{{
iab compta comptabilité
iab princch principe du coût historique
iab prod production
iab cot coût
iab pouva pouvoir d'achat
iab princp principe de prudence
iab opé opération
iab déc décembre
iab janv janvier
iab oct octobre
iab nov novembre
iab fév février
iab juil juillet
iab sept septembre
iab pcg plan comptable général
iab com compte
"}}}
"------------------------------
"Microeconomics {{{
iab conso consommation
iab efsu effet de substitution
iab conbu contrainte de budjet
iab efre effet revenu
iab oftr offre de travail
iab lode loi de la demande
iab loof loi de l'offre
iab sal salaire
iab tms taux marginal de substitution
iab eqin équilibre intertemporel du consommateur
iab macroéco macroéconomie
iab microéco microéconomie
iab tain taux d'intérêt
iab bifu biens futurs
iab bipr biens présents
iab exo exercice
"}}}
"------------------------------
"abbreviations cours moreno {{{
iab Letat L'État
iab AC Amérique Centrale
"}}}
"------------------------------
"abb cours macroéconomie {{{
iab lt long terme
iab ct court terme
iab flex flexibilité
iab monn monnétaire
iab qtite quantité
iab thqumo théorie quantitative de la monnaie
iab pop population
iab hypo hypothèse
iab BC Banque Centrale
iab fct fonction
iab dép dépenses
iab enc encaisse
iab prop proportion
iab indivi individus
iab c_phi courbe de Phillips
"}}}
"------------------------------
"Histoire des idées économique {{{
iab maiinv main invisible
iab intgé intérêt général
iab perso personnel
iab ex exemple
iab smith Smith
iab dt division du travail
iab poac pouvoir d'achat

"}}}
"-----------------------------------------------------------------------
"To enter other abbreviation without the need
"to open this file, see .vim/vimrc/vimrc_mapping_and_plugins for more details.
"Basically you have to select the word or the expression you wish to abbreviate
"and then, to push Shift+F8. A dialogue will ask what will be the abbreviation
"you wish to use, and will register it bellow.
"----------------------------------------------------------------------
"}}}
" "========================================================================="
" FUNCTIONS
" "========================================================================="
"{{{ Function to surround text and its mappings
"-------------------------------
fun! Surround(s1, s2) range
  exe "normal vgvmboma\<Esc>"
  normal `a
  let lineA = line(".")
  let columnA = col(".")
  normal `b
  let lineB = line(".")
  let columnB = col(".")
  " exchange marks
  if lineA > lineB || lineA <= lineB && columnA > columnB
    " save b in c
    normal mc
    " store a in b
    normal `amb
    " set a to old b
    normal `cma
  endif
  exe "normal `ba" . a:s2 . "\<Esc>`ai" . a:s1 . "\<Esc>"
endfun
"----------------------
"mapping to use it
"for more details, see here :
"http://vim.wikia.com/wiki/Surround_selection_with_text
"----------------------
vnoremap _" :call Surround('"', '"')<CR>
vnoremap _( :call Surround('(', ')')<CR>
vnoremap _[ :call Surround('[', ']')<CR>
vnoremap _{ :call Surround('{', '}')<CR>
vnoremap _$ :call Surround('$', '$')<CR>
nnoremap _$ :call Surround('$', '$')<CR>
vnoremap _em :call Surround('\emph{', '}')<CR>
nnoremap _em :call Surround('\emph{', '}')<CR>
vnoremap _bf :call Surround('\textbf{', '}')<CR>
nnoremap _bf :call Surround('\textbf{', '}')<CR>
vnoremap _lr :call Surround('\left', '\right')<CR>
nnoremap _lr :call Surround('\left', '\right')<CR>

"}}}
" "========================================================================="
"{{{ Greek letters, AucTex style bindings
" "========================================================================="
"---------------------------------------------------------------------
"From auctex.vim, [url]http://www.vim.org/scripts/script.php?script_id=162[/url]
"---------------------------------------------------------------------
"No timeout.  Applies to mappings such as `a for \alpha
set notimeout

inoremap <buffer> <Leader><Leader> <Leader>
inoremap <buffer> <Leader>a \alpha
inoremap <buffer> <Leader>b \beta
inoremap <buffer> <Leader>c \chi
inoremap <buffer> <Leader>d \delta
inoremap <buffer> <Leader>e \varepsilon
inoremap <buffer> <Leader>f \varphi
inoremap <buffer> <Leader>g \gamma
inoremap <buffer> <Leader>h \eta
inoremap <buffer> <Leader>i \int_{}^{}<Esc>F}i
        " Or \iota or \infty or \in
inoremap <buffer> <Leader>k \kappa
inoremap <buffer> <Leader>l \lambda
inoremap <buffer> <Leader>m \mu
inoremap <buffer> <Leader>n \nu
inoremap <buffer> <Leader>o \omega
inoremap <buffer> <Leader>p \pi
inoremap <buffer> <Leader>q \theta
inoremap <buffer> <Leader>r \rho
inoremap <buffer> <Leader>s \sigma
inoremap <buffer> <Leader>t \tau
inoremap <buffer> <Leader>u \upsilon
inoremap <buffer> <Leader>v \vee
inoremap <buffer> <Leader>w \wedge
inoremap <buffer> <Leader>x \xi
inoremap <buffer> <Leader>y \psi
inoremap <buffer> <Leader>z \zeta
inoremap <buffer> <Leader>D \Delta
inoremap <buffer> <Leader>I \int_{}^{}<Esc>F}i
inoremap <buffer> <Leader>F \Phi
inoremap <buffer> <Leader>G \Gamma
inoremap <buffer> <Leader>L \Lambda
inoremap <buffer> <Leader>N \nabla
inoremap <buffer> <Leader>O \Omega
inoremap <buffer> <Leader>Q \Theta
inoremap <buffer> <Leader>R \varrho
inoremap <buffer> <Leader>S \sum_{}^{}<Esc>F}i
inoremap <buffer> <Leader>U \Upsilon
inoremap <buffer> <Leader>X \Xi
inoremap <buffer> <Leader>Y \Psi
inoremap <buffer> <Leader>0 \emptyset
inoremap <buffer> <Leader>1 \left
inoremap <buffer> <Leader>2 \right
inoremap <buffer> <Leader>3 \Big
inoremap <buffer> <Leader>6 \partial
inoremap <buffer> <Leader>8 \infty
inoremap <buffer> <Leader>/ \frac{}{}<Esc>F}i
inoremap <buffer> <Leader>% \frac{}{}<Esc>F}i
inoremap <buffer> <Leader>@ \circ
inoremap <buffer> <Leader>\| \Big\|
inoremap <buffer> <Leader>= \equiv
inoremap <buffer> <Leader>\ \setminus
inoremap <buffer> <Leader>. \cdot
inoremap <buffer> <Leader>* \times
inoremap <buffer> <Leader>& \wedge
inoremap <buffer> <Leader>- \bigcap
inoremap <buffer> <Leader>+ \bigcup
inoremap <buffer> <Leader>( \subset
inoremap <buffer> <Leader>) \supset
inoremap <buffer> <Leader>< \leq
inoremap <buffer> <Leader>> \geq
inoremap <buffer> <Leader>, \nonumber
inoremap <buffer> <Leader>: \dots
inoremap <buffer> <Leader>~ \tilde{}<Left>
inoremap <buffer> <Leader>^ \hat{}<Left>
inoremap <buffer> <Leader>; \dot{}<Left>
inoremap <buffer> <Leader>_ \bar{}<Left>
inoremap <buffer> <Leader><M-c> \cos
inoremap <buffer> <Leader><C-E> \exp\left(\right)<Esc>F(a
inoremap <buffer> <Leader><C-I> \in
inoremap <buffer> <Leader><C-J> \downarrow
inoremap <buffer> <Leader><C-L> \log
inoremap <buffer> <Leader><C-P> \uparrow
inoremap <buffer> <Leader><Up> \uparrow
inoremap <buffer> <Leader><C-N> \downarrow
inoremap <buffer> <Leader><Down> \downarrow
inoremap <buffer> <Leader><C-F> \to
inoremap <buffer> <Leader><Right> \lim_{}<Left>
inoremap <buffer> <Leader><C-S> \sin
inoremap <buffer> <Leader><C-T> \tan
inoremap <buffer> <Leader><M-l> \ell
inoremap <buffer> <Leader><CR> \nonumber\\<CR><HOME>&&<Left>
" }}}
" "========================================================================="
" Format the paragraph   {{{
" Due to Ralf Aarons
" In normal mode, gw formats the paragraph (without splitting dollar signs).
function! s:TeX_par()
    if (getline('.') != '')
        let par_begin = '^$\|^\s*\\end{\|^\s*\\\]'
        let par_end = '^$\|^\s*\\begin{\|^\s*\\\['
        call search(par_begin, 'bW')
        "call searchpair(par_begin, '', par_end, 'bW')
        +
    let l = line('.')
        normal! V
        call search(par_end, 'W')
        "call searchpair(par_begin, '', par_end, 'W')
        -
    if l == line('.')
        normal! 
    endif
    normal Q
    "normal! Q
    endif
endfun
nmap <buffer><silent> gw :call <SID>TeX_par()<CR>

" }}}
" "========================================================================="
" Smart quotes.   {{{
" Thanks to Ron Aaron <ron@mossbayeng.com>.
function! s:TexQuotes()
    let insert = "''"
    let left = getline('.')[col('.')-2]
    if left =~ '^\(\|\s\)$'
    let insert = '``'
    elseif left == '\'
    let insert = '"'
    endif
    return insert
endfunction
inoremap <buffer> " <C-R>=<SID>TexQuotes()<CR>

" }}}
" "========================================================================="
" _{} and ^{}   {{{

" Typing __ results in _{}
function! s:SubBracket()
    let insert = '_'
    let left = getline('.')[col('.')-2]
    if left == '_'
    let insert = "{}\<Left>"
    endif
    return insert
endfunction
inoremap <buffer><silent> _ <C-R>=<SID>SubBracket()<CR>

" Typing ^^ results in ^{}
function! s:SuperBracket()
    let insert = '^'
    let left = getline('.')[col('.')-2]
    if left == '^'
    let insert = "{}\<Left>"
    endif
    return insert
endfunction
inoremap <buffer><silent> ^ <C-R>=<SID>SuperBracket()<CR>

" }}}
" "========================================================================="
" Bracket Completion Macros   {{{

" Key Bindings                {{{

" Typing the symbol a second time (for example, $$) will result in one
" of the symbole (for instance, $).  With {, typing \{ will result in \{\}.

imap <buffer><silent> ( <C-R>=<SID>Double('(',')<++>')<CR><ESC>3hi
"inoremap <buffer><silent> [ <C-R>=<SID>Double('[',']')<CR>
"inoremap <buffer><silent> [ <C-R>=<SID>CompleteSlash('[',']')<CR>
imap <buffer><silent> $ <C-R>=<SID>Double('$','$<++>')<CR><ESC>3hi
"inoremap <buffer><silent> & <C-R>=<SID>DoubleAmpersands()<CR>
"inoremap <buffer><silent> { <C-R>=<SID>CompleteSlash('{','}')<CR>
"inoremap <buffer><silent> \| <C-R>=<SID>CompleteSlash("\|","\|")<CR>

"When I write a file, if I have forgoten a $$ for math variables for example,
"enabling completion of $ is a problem, since I can't surround it with the
"previously defined function for surrounding. Therefore, I need something to
"enable and disable completion

function! EnableBracketCompletion()
    imap <buffer><silent> ( <C-R>=<SID>Double('(',')<++>')<CR><ESC>3hi
    "inoremap <buffer><silent> [ <C-R>=<SID>Double('[',']')<CR>
    "inoremap <buffer><silent> [ <C-R>=<SID>CompleteSlash('[',']')<CR>
    imap <buffer><silent> $ <C-R>=<SID>Double('$','$<++>')<CR><ESC>3hi
    "inoremap <buffer><silent> & <C-R>=<SID>DoubleAmpersands()<CR>
    "inoremap <buffer><silent> { <C-R>=<SID>CompleteSlash('{','}')<CR>
    "inoremap <buffer><silent> \| <C-R>=<SID>CompleteSlash("\|","\|")<CR>
endfunction

function DisableBracketCompletion()
    iunmap <buffer><silent> ( <C-R>=<SID>Double('(',')<++>')<CR><ESC>3hi
    "inoremap <buffer><silent> [ <C-R>=<SID>Double('[',']')<CR>
    "inoremap <buffer><silent> [ <C-R>=<SID>CompleteSlash('[',']')<CR>
    iunmap <buffer><silent> $ <C-R>=<SID>Double('$','$<++>')<CR><ESC>3hi
    "inoremap <buffer><silent> & <C-R>=<SID>DoubleAmpersands()<CR>
    "inoremap <buffer><silent> { <C-R>=<SID>CompleteSlash('{','}')<CR>
    "inoremap <buffer><silent> \| <C-R>=<SID>CompleteSlash("\|","\|")<CR>
endfunction


imap <F5> <ESC>:call DisableBracketCompletion()<CR>
nmap <F5> <ESC>:call DisableBracketCompletion()<CR>

imap <S-F5> <ESC>:call EnableBracketCompletion()<CR>
nmap <S-F5> <ESC>:call EnableBracketCompletion()<CR>

" If you would rather insert $$ individually, the following macro by 
" Charles Campbell will make the cursor blink on the previous dollar sign,
" if it is in the same line.
" inoremap <buffer> $ $<C-O>F$<C-O>:redraw!<CR><C-O>:sleep 500m<CR><C-O>f$<Right>

" }}}

" Functions         {{{

" For () and $$
function! s:Double(left,right)
    if strpart(getline('.'),col('.')-2,2) == a:left . a:right
    return "\<Del>"
    else
    return a:left . a:right . "\<Left>"
    endif
endfunction

" Complete [, \[, {, \{, |, \|
function! s:CompleteSlash(left,right)
    let column = col('.')
    let first = getline('.')[column-2]
    let second = getline('.')[column-1]
    if first == "\\"
    if a:left == '['
        return "\[\<CR>\<CR>\\]\<Up>"
    else
        return a:left . "\\" . a:right . "\<Left>\<Left>"
    endif
    else
    if a:left =~ '\[\|{'
    \ && strpart(getline('.'),col('.')-2,2) == a:left . a:right
        return "\<Del>"
        else
            return a:left . a:right . "\<Left>"
    endif
    endif
endfunction

" Double ampersands, if you are in an eqnarray or eqnarray* environment.
function! s:DoubleAmpersands()
    let stop = 0
    let currentline = line('.')
    while stop == 0
    let currentline = currentline - 1
    let thisline = getline(currentline)
    if thisline =~ '\\begin' || currentline == 0
        let stop = 1
    endif
    endwhile
    if thisline =~ '\\begin{eqnarray\**}'
    return "&&\<Left>"
    elseif strpart(getline('.'),col('.')-2,2) == '&&'
    return "\<Del>"
    else
    return '&'
    endif
endfunction

" }}}

" }}}
" "========================================================================="
" Matching Brackets Macros using <Insert><Insert>.   {{{
" (due to Saul Lubkin).  For normal mode.

" Double insert key macros for working with brackets   {{{
" The cursor must be over a bracket, in normal mode.

function! s:DoubleInsert()
    let c = nr2char(getchar())
    if c == "d"
    call <SID>DeleteBrackets()
    elseif c == "("
    call <SID>ChangeRound()
    elseif c == ")"
    call <SID>ChangeRound()
    elseif c == "["
    call <SID>ChangeSquare()
    elseif c == "]"
    call <SID>ChangeSquare()
    elseif c == "{"
    call <SID>ChangeCurly()
    elseif c == "}"
    call <SID>ChangeCurly()
    elseif c == "l"
    call <SID>PutLeftRight()
    elseif c == "p"
    call <SID>PutBigg()
    elseif c == "c"
    call <SID>ChangeLeftRightBigg()
    endif
endfunction
    
noremap <buffer><silent> ,ib :echo "Brackets: d: del  ()[]{}: change  l: \\left  p: prefix  c: change\n\n"<CR>:call <SID>DoubleInsert()<CR>

noremap <buffer><silent> <C-Del> :call <SID>DeleteBrackets()<CR>
inoremap <buffer><silent> <C-BS> <Left><C-O>:call <SID>DeleteBrackets()<CR>

" }}}
" Functions   {{{

" Delete matching brackets.
function! s:DeleteBrackets()
    let bb = getline('.')[col('.') - 2]
    let cc = getline('.')[col('.') - 1]
    if bb == '\' && cc =~ '{\|}'
    normal! X%X%
    endif
    if cc =~ '{\|\[\|('
    normal! %x``x
    elseif cc =~ '}\|\]\|)'
    normal! %%x``x``
    endif
endfunction

" Put \left...\right in front of the matched brackets.
function! s:PutLeftRight()
    let previous = getline('.')[col('.') - 2]
    let char = getline('.')[col('.') - 1]
    if previous == '\'
    if char == '{'
    execute "normal! ileft\\\<Esc>l%iright\\\<Esc>l%"
    elseif char == '}'
    execute "normal! iright\\\<Esc>l%ileft\\\<Esc>l%"
    endif
    elseif char =~ '\[\|('
    execute "normal! i\\left\<Esc>l%i\\right\<Esc>l%"
    elseif char =~ '\]\|)'
    execute "normal! i\\right\<Esc>l%i\\left\<Esc>l%"
    endif
endfunction

" Look at the 'string', and return either 'default' or the string.
function! s:StripSlash(string,default)
    let len = strlen(a:string)
    if a:string[0] == '\'
    return strpart(a:string, 1, len-1)
    elseif len == 0
    return a:default
    else
    return '\' . a:string
    endif
endfunction

" Put \Big (or whatever the reader chooses) in front of the matched brackets.
function! s:PutBigg()
    let in = input("\\big, \\bigg, or what? (default: \\Big):  \\")
    let in = <SID>StripSlash(in,"\\Big")
    let b = getline('.')[col('.') - 2]
    let c = getline('.')[col('.') - 1]
    if b == '\'
    execute "normal! hi" . in . "\<Esc>l%hi" . in . "\<Esc>l%"
    elseif c =~ '{\|\[\|(\|}\|\]\|)'
    execute "normal! i" . in . "\<Esc>l%i" . in . "\<Esc>l%"
    endif
endfunction

" Change \left..\right to \bigg, or whatever the user chooses.
function! s:ChangeLeftRightBigg()
    let in = input("\\Big, \\bigg, or what? (default: nothing):  \\")
    let in = <SID>StripSlash(in,'')
    let b = getline('.')[col('.') - 2]
    let c = getline('.')[col('.') - 1]
    if b == '\'
      if c =~ '{\|}'
    execute "normal! 2F\\xcw" . in . "\<Esc>2l%2F\\xcw" . in . "\<Esc>2l%"
      endif
    elseif c =~ '\[\|(\|\]\|)'
      execute "normal! F\\xcw" . in . "\<Esc>l%F\\xcw" . in . "\<Esc>l%"
    endif
endfunction

" Change the brackets to curly brackets.
function! s:ChangeCurly()
    let c = getline('.')[col('.') - 1]
    if c =~ '\[\|('
    execute "normal! i\\{\<Esc>l%i\\\<Esc>lr}``xh"
    elseif c =~ '\]\|)'
    execute "normal! %i\\{\<Esc>l%i\\\<Esc>lr}``xh%"
    endif
endfunction

" Change the brackets to round brackets.
function! s:ChangeRound()
    let b = getline('.')[col('.') - 2]
    let c = getline('.')[col('.') - 1]
    if b == '\'
    if c == '{'
        normal! %Xr)``Xr(
    elseif c == '}'
        normal! %%Xr)``Xr(``
    endif
    elseif c == '['
    normal! %r)``r(
    elseif c == ']'
    normal! %%r)``r(%
    endif
endfunction

" Change the brackets to square brackets.
function! s:ChangeSquare()
    let b = getline('.')[col('.') - 2]
    let c = getline('.')[col('.') - 1]
    if b == '\'
    if c == '{'
        normal! %Xr]``Xr[
    elseif c == '}'
        normal! %%Xr]``Xr[``
    endif
    elseif c == '('
    normal! %r]``r[
    elseif c == ')'
    normal! %%r]``r[%
    endif
endfunction

" }}}

" vim:fdm=marker

Voilà ! 1 de ces 4, de toute façon je finirai ma configuration, et je ferai un
post pour le signaler si ça t'intéresse, toi ou d'autres.

Bonne soirée !
mondai

Hors ligne

#45 Le 25/10/2010, à 22:13

tshirtman

Re : Enjoliver un fichier tex : vim ou emacs ?

merci smile je vais essayer de lire ça en profondeur, j'ai appercu des mappings sympa déjà ^^.

Hors ligne