"" vim:ft=vim:fdm=marker:tw=78
""
"" vimrc:
""   initialization for for the allmighty vim :)
""

    " use vim settings, rather then vi settings;
    " this must be first, because it changes other options as a side effect.
set nocompatible

"" settings, you don't want to set permanently
" {{{

    " runtimepath, should be setup correctly by vim
"set rtp=foobar

    " the main help file. should be setup by vim, too
"set hf=barbaz

    " nroff macro for paragraphs (keep default!)
"set paragraphs=

    " nroff macro for sections (keep default!)
"set sections=

    " width of the terminal (vim should set this itself)
"set columns=80

    " height of the terminal
"set lines=25

    " should be handled by colorschemes
"set background=dark

    " handled automatically
"set filetype=perl

    " :help 'syntax'
"set syntax=c

    " handled by syntax files
"set highlight=foobarbaz

    " handled by ChooseLang() below
"set spell

    " ditto
"set spelllang=de

    " ditto
"set spellfile=/foobar/baz

    " keep current window at same height
"set winfixheight

    " keep current window at same width
"set winfixwidth

    " identifies the preview window
"set previewwindow

    " scroll current window with other scroll bound ones
"set scrollbind

    " vim should set this up
"set term=xterm

    " ...well...
"set modified

    " vim takes care
"set readonly

    " and again...
"set modifiable

    " filetypes should handle this
"set comments=foo

    " pattern for recognizing macro defines
"set define=^\s*#\s*define

    " pattern for recognizing file includes
"set include=^\s*#\s*include

    " how to turn an include string into a filename
"set includeexpr=

"}}}

"" core settings
"{{{

    " keep N lines of history (for various purposes)
    " merely a fallback (see viminfo)
set history=250

    " read/write a .viminfo file
    "       'N  - keep the registeres for N files
    "       "N  - how many lines to save per register
    "       fN  - keep global regs? yes: N==1; no N==0
    "       :N  - keep N :commands
    "       /N  - keep N search patterns
    "       @N  - keep N items of input-line history
    "             see ':help input()'
    "       h   - no hlsearch when starting up
set viminfo='250,\"250,f1,:500,/500,@500,h

    " keep a backup file
set backup

    " default vim way of handling special chars in patterns
set magic

    " vi compatibility options
set cpoptions=aABceFs

    " when searching, do not ignore case in patterns
set noignorecase

    " no, don't be smart. for once.
set nosmartcase

    " details about switching letter case
set casemap=internal,keepascii

    " max memory (in KiB) used for pattern matching
set maxmempattern=1000

    " :help 'display'
set display=lastline,uhex

    " msecs delay for chars to be displayed (debugging only!)
set writedelay=0

    " if set, redrawing is more relaxed
set nolazyredraw

    " max number of cols to look for syntax items
set synmaxcol=3000

    " warn if while running shell commands and a buffer changes
set warn

    " :help 'hidden'
set nohidden

    " verbosity level
set verbose=0

    " file for verbosity messages
set verbosefile=

    " english docs
set helplang=en

    " how many undo levels?
set undolevels=1000

    " don't limit textwith by default
set textwidth=0

    " recognizes special keys that send sequences that start with an
    " escape character
set esckeys

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

    " don't do anything special about the keyboard
set keymodel=

    " behave a little more like vi does
set whichwrap=

    " set a searchpath for files
set path=.,/usr/include,,

    " set a searchpath for :cd
set cdpath=

    " swapfiles should not be saved in the current directory
set directory=~/tmp,/tmp

    " how to search for tag files
set tags+=tags;/

"}}}

"" terminal settings
"{{{

    " redraw instead of scrolling after this amount if lines
set ttyscroll=500

    " use internal termcap entries
set ttybuiltin

    " this is a good idea on most terminals; toggle off for really slow ones
set ttyfast

    " terminal with a lot of colours?
if &t_Co > 8 && !has("gui_running")
    set t_AB=^[[48;5;%dm
    set t_AF=^[[38;5;%dm
endif

"}}}

"" user interface
"{{{

    " show the commands that i am typing
set showcmd

    " -- INSERT -- ; -- REPLACE --
set showmode

    " show the cursor position all the time
set ruler
set rulerformat=%20(%=%-14(%l,%c%V%)\ %P%)

    " menucompletion for vim's :commandline
set wildmenu
set wildmode=full

    " wrap around the endoffile when searching
set wrapscan

    " shorten some messages
set shortmess=aoOtTI

    " don't move to the 1st non-blank char after certain commands
set nostartofline

    " always tell me how many lines I changed
set report=0

    " marks the line in which the cursor is
set nocursorline

    " marks the column in which the cursor is
set nocursorcolumn

    " Put the information I want into the status line and *always*
    " show the statusline in the last-but-one line of the screen.
set statusline=%!FTStatuslineSet()
set laststatus=2

    " the tabline feature is rather nice.
    " showtabline=2 will always display that line.
set showtabline=2
set tabpagemax=128
set tabline=%!FTTablineSet()

    " normally, i'm on dark backgrounds
set background=dark

    " do not start insert mode by default
set noinsertmode

    " don't enter paste mode by default (use F2 to toggle)
set nopaste

    " incremental search
set incsearch

    " ^U and ^D should scroll how many lines?
set scroll=8

    " like scroll, but for horizontal scrolling
set sidescroll=1

    " keep a few lines above/below the cursor even if we are
    " moving the cursor towards the top/bottom of the page
set scrolloff=4

    " similar to scrolloff, but for horizontal scrolling
set sidescrolloff=2

    " if on, wraps long lines on the right side of the term
set wrap

    " when on, use chars in 'breakat' to wrap long lines
set linebreak

    " see 'linebreak'
set breakat=\ !@*-+;:,./?

    " a marker to highlight wrapped lines
set showbreak=->

    " :help 'fillchars'
set fillchars=stl:\ ,stlnc:_,vert:\|,fold:.,diff:\-

    " use listchars, to display special chars
set list
set listchars=eol:-,tab:,trail:·,extends:>,precedes:<,nbsp:%

    " if set, display line numbers
set nonumber

    " number of columns to use for the line number
set numberwidth=4

    " the height of the :command line
set cmdheight=1

    " when splitting windows make every window equally big
set equalalways

    " directions to use for 'equalalways'
set eadirection=both

    " minimum height of the current window
set winheight=1

    " minimum width of the current window
set winwidth=20

    " minimum height of any window
set winminheight=1

    " minimum width of any window
set winminwidth=1

    " initial height of help window
set helpheight=20

    " default height for the preview window
set previewheight=12

    " default format options
set formatoptions=tcroqn1l

    " :help 'switchbuf'
set switchbuf=

    " use more prompt when listings are too long
set more

    " :help 'confirm'
set noconfirm

    " never *ever* use bells
set noerrorbells

    " visual bell is ugly, too
set novisualbell

    " don't wrap artificially
set wrapmargin=0

    " new window below current
set nosplitbelow

    " new windows created right of the current one
set nosplitright

    " :help 'selection'
set selection=inclusive

    " no select mode
set selectmode=

    " options for 'scrollbind'
set scrollopt=ver,jump

    " how many lines to scroll at a time
set scrolljump=1

    " always set autoindenting on
set autoindent

    " don't use 2 spaces when joining lines that end in a dot
set nojoinspaces

set matchpairs=(:),{:},[:],<:>

    " default folding method
set foldmethod=marker

    " use search highlighting
set hlsearch

    " never ever use X11 clipboard
set clipboard=exclude:.*

"}}}

"" gui settings
"{{{

if (has("gui_running"))

    if (has("win32"))
        set guifont=Courier_New:h9:cANSI
        autocmd GUIEnter * simalt ~x
    else
        set guifont=Terminus\ 8
    endif

    " well, it gets better in gvim. Still it's a darn slow feature...
    "set cursorline
    "set cursorcolumn

    " don't use the mouse for anything. ever.
    set mouse=

endif

set guioptions=M

"}}}

"" insertion completion
"{{{

set completeopt=menu,longest

    " limit size of omnicompletion menu
set pumheight=12

"}}}

"" spelling correction
"{{{

    " where to assume end of sentences
set spellcapcheck=[.?!]\\_[\\])'\"\ ]\\+

    " method for spelling suggestions
set spellsuggest=best

    " tune when to start compressing the word tree
set mkspellmem=460000,2000,500

    " colorization for vim's spellchecking
    " TODO: possibly move this to colors/ftcolor.vim
hi SpellBad   ctermfg=white ctermbg=red
hi SpellCap   ctermfg=white ctermbg=green
hi SpellRare  ctermfg=black ctermbg=yellow
hi SpellLocal ctermfg=black ctermbg=white

"}}}

"" setup for certain scripts
"{{{

"" 2html.vim setup
"{{{

let html_number_lines   = 0
let html_ignore_folding = 1
"let html_use_css
"let html_no_pre
"let use_xhtml

"}}}

"" taglist setup
"{{{

let Tlist_Use_Right_Window  = 1
let Tlist_Sort_Type         = 'name'
let Tlist_WinWidth          = 30
let Tlist_Display_Prototype = 0
let Tlist_Exit_OnlyWindow   = 1
let Tlist_Close_On_Select   = 1

"}}}

"}}}

"" additional setup for some filetype plugins
"{{{

    " debian filetypes default folding ON
let g:debchangelog_fold_enable = 1
let g:debcontrol_fold_enable = 1

    " set variables for perl.vim
let perl_fold = 1

    " load doxygen syntax per default
let g:load_doxygen_syntax = 1
let g:doxygen_enhanced_colour = 0
let doxygen_my_rendering = 0
let doxygen_javadoc_autobrief = 0
let doxygen_end_punctuation = '[.]'

"}}}

    " load ftplugins
filetype plugin on

    " use my own colorscheme
colorscheme ftcolor

    " set the screen hardstatus to vim(filename.ext)
if ((&term =~ '^screen' && $VIM_PLEASE_SET_TITLE =~ '^yes$') || has('gui_running'))
    set t_ts=^[k
    set t_fs=^[\
    set title
    if (has('gui_running'))
        autocmd BufEnter * let &titlestring = "vim(" . expand("%:t") .
            \ ") (GUI vim)"
    else
        autocmd BufEnter * let &titlestring = "vim(" . expand("%:t") . ")"
    endif

    if (&shell !~ '^\(.*/\|\)zsh')
        " my zsh setup sets the hardstatus to 'zsh' when printing
        " a prompt anyway. This is a workaround for systems, that
        " do not do such magic by default.
        let &titleold = fnamemodify(&shell, ":t")
    endif
endif

"" abbreviations
"{{{

abbreviate _ce_ /**/
abbreviate _cb_ {<CR>}
abbreviate _em_ ft@bewatermyfriend.org

"}}}

"" autocommands
"{{{

if has("autocmd")

        " when using omnicomlete's preview feature; close the preview window,
        " as soon as the popup menu closes.
    "autocmd CursorMovedI * if !pumvisible() | pclose | endif

        " set filetype to txt2tags for t2t files
    autocmd BufRead *.t2t set ft=txt2tags

        " In text files, always limit the width of text to 78 characters
    autocmd BufRead *.txt set tw=78

        " settings for tex
    autocmd BufNewFile,BufRead *.tex set ft=tex
    autocmd BufNewFile,BufRead *.tex set tw=78

        " use ikiwiki.vim for markdown files
    autocmd BufNewFile,BufRead *.mdwn set ft=ikiwiki

        " fvwm is in version 2
    autocmd FileType fvwm           let b:fvwm_version=2

        " remind's reminder files
    autocmd FileType remind set notitle

        " When starting to edit a file:
        "   For C and C++ files set formatting of comments and set C-indenting
        "   on. For other files switch it off. Don't change the order, it's
        "   important that the line with * comes first.
    autocmd FileType *          set formatoptions=tcql  nocindent   comments&

    autocmd FileType c,cpp      set formatoptions=croql
    autocmd FileType c,cpp      set cindent
    autocmd FileType c,cpp      set comments=sr:/*,mb:*,el:*/,://
    autocmd FileType c,cpp      set foldmethod=syntax
    autocmd FileType c,cpp      set foldnestmax=1
    if &columns >= 85
        autocmd FileType c,cpp  set foldcolumn=2
    endif
    autocmd FileType c,cpp      set foldlevel=99
                            " >     normal indent
                            " e     additional indent for stuff inside braces
                            " n     additional indent code after if (etc)
                            "       without following braces
                            " f     first opening brace
                            " {     opening braces
                            " }     closing braces
                            " ^     additional indent first indention
                            " :     case labels
                            " =     idention after case labels
                            " l     case labels
                            " b     indention of final break in switch() { ... }
                            " g     c++ scope declarations
                            " h     c++ indention after scope labels
                            " p     parameter idention for k&r style code
                            " t     indent for type declaration on its own line
                            " i     c++ class decl and constructor indent
                            " +     indention of continuation lines
                            " c     comment indention
                            " C     see :help (comments with non-default openers)
                            " /     additional indent for comments
                            " (     additional indent for lines with unclosed parens
                            " u     same as ( but one level deeper
                            " U     see :help (unclosed parens with ')' as the
                            "       1st non-whitespace character)
                            " w     unclosed parens; alignment to to first condition
                            " W     unclosed parens with the opening paren as
                            "       the last non-ws character on the previous line
                            " m     align closing braces to lines of the opening one
                            " M     do not align closing braces the the opening one
                            " j     indent anon java classes correctly
                            " )     how many lines to search for unclosed parens
                            " *     how many lines to search for unclosed comments
                            " #     recognize shell/Perl comments
    autocmd FileType c,cpp
    \ set cinoptions=>s,e0,f0,{0,}0,^0,:0,=s,l1,b0,g0,h0,ps,t0,is,+s,c3,C0,/0,(0,u0,U0,w1,Ws,m1,M0,j1,)20,*30,#0
    "autocmd FileType c,cpp,perl nnoremap <silent> <F7>  :Tlist<CR>
    "autocmd FileType c,cpp,perl nnoremap <silent> <F8>  :TlistUpdate<CR>
    "autocmd FileType c,cpp,perl nnoremap <silent> <F9>  :TlistSync<CR>
    "autocmd FileType c,cpp      nnoremap <silent> <F10> :TlistAddFilesRecursive . *.[ch]<CR>
    "autocmd FileType perl       nnoremap <silent> <F10> :TlistAddFilesRecursive . *.pl *.pm<CR>

    autocmd FileType perl       set foldmethod=syntax
    autocmd FileType perl       so $VIMRUNTIME/indent/perl.vim
    autocmd FileType perl       set formatoptions=croql cindent
    autocmd FileType perl       compiler perlcritic

    autocmd FileType c,cpp,matlab,perl
        \ match     LineTooLong /\%80v./

    autocmd FileType matlab     set foldcolumn=4

    augroup gzip
    au!

        " Enable editing of gzipped files
        " set binary mode before reading the file
    autocmd BufReadPre,FileReadPre      *.gz,*.bz2  set bin
    autocmd BufReadPost,FileReadPost    *.gz        call GZIP_read("gunzip")
    autocmd BufReadPost,FileReadPost    *.bz2       call GZIP_read("bunzip2")
    autocmd BufWritePost,FileWritePost  *.gz        call GZIP_write("gzip")
    autocmd BufWritePost,FileWritePost  *.bz2       call GZIP_write("bzip2")
    autocmd FileAppendPre               *.gz        call GZIP_appre("gunzip")
    autocmd FileAppendPre               *.bz2       call GZIP_appre("bunzip2")
    autocmd FileAppendPost              *.gz        call GZIP_write("gzip")
    autocmd FileAppendPost              *.bz2       call GZIP_write("bzip2")

        " After reading compressed file: Uncompress text in buffer with "cmd"
    fun! GZIP_read(cmd)
            " set 'cmdheight' to two, to avoid the hit-return prompt
        let ch_save = &ch
        set ch=3
            " when filtering the whole buffer, it will become empty
        let empty = line("'[") == 1 && line("']") == line("$")
        let tmp = tempname()
        let tmpe = tmp . "." . expand("<afile>:e")
            " write the just read lines to a temp file "'[,']w tmp.gz"
        execute "'[,']w " . tmpe
            " uncompress the temp file "!gunzip tmp.gz"
        execute "!" . a:cmd . " " . tmpe
            " delete the compressed lines
        '[,']d
            " read in the uncompressed lines "'[-1r tmp"
        set nobin
        execute "'[-1r " . tmp
            " if buffer became empty, delete trailing blank line
        if empty
            normal Gdd''
        endif
            " delete the temp file
        call delete(tmp)
        let &ch = ch_save
            " When uncompressed the whole buffer, do autocommands
        if empty
            execute ":doautocmd BufReadPost " . expand("%:r")
        endif
    endfun

        " After writing compressed file: Compress written file with "cmd"
    fun! GZIP_write(cmd)
        if rename(expand("<afile>"), expand("<afile>:r")) == 0
            execute "!" . a:cmd . " <afile>:r"
        endif
    endfun

        " Before appending to compressed file: Uncompress file with "cmd"
    fun! GZIP_appre(cmd)
        execute "!" . a:cmd . " <afile>"
        call rename(expand("<afile>:r"), expand("<afile>"))
    endfun

    augroup END

endif
"}}}

"" syntax
"{{{

    " Switch syntax highlighting on, when the terminal has colors.
if &t_Co > 2 || has("gui_running")
    syntax on
endif

"}}}

"" highlights
"{{{

   "highlight WhitespaceEOL ctermbg=blue
   "match     WhitespaceEOL /\s\+$/

"}}}

"" functions
"{{{

function FTToggleColor()
    "{{{
    if (g:colors_name != 'ftcolor' && g:colors_name != 'ftcolight')
        echo "Sorry, currently not using any ftco* scheme"
        return
    endif

    if (g:colors_name == 'ftcolor')
        colorscheme ftcolight
    else
        colorscheme ftcolor
    endif
    "}}}
endfunction

function ChooseLang(arg)
    "{{{
    if a:arg == '__interactive__'
        let opt = inputlist(
                          \ [ "Choose Spellcheck Language:",
                            \ " 1    German",
                            \ " 2    English",
                            \ " 3    Toggle (off/last choosen value)"
                          \ ]
                \ )
    elseif a:arg == '__init__'
        set nospell
        set spelllang=de
        set dictionary=/usr/share/dict/ogerman
        return
    else
        let opt = a:arg
    endif
    if     opt == 0
        return
    elseif opt == 1
        set spell
        set spelllang=de
        set dictionary=/usr/share/dict/ogerman
    elseif opt == 2
        set spell
        set spelllang=en
        set dictionary=/usr/share/dict/american-english
    elseif opt == 3
        set invspell
    else
        echo "Unknown value: " . opt
    endif
    "}}}
endfunction

function ChooseIndent(arg)
    "{{{
    if a:arg == '__interactive__'
        let opt = inputlist(
                          \ [ "Choose indenting Style:",
                            \ " 1    two space indention (no mixing)",
                            \ " 2    four space indention (no mixing)",
                            \ " 3    four space indention (no mixing) [tabs 8 chars wide]",
                            \ " 4    eight space indention (no mixing)",
                            \ " 5    tab indention (8 chars wide)",
                            \ " 6    tab indention (4 chars wide)",
                            \ " 7    mixed indention, 2 chars (8 chars replaced by tab)",
                            \ " 8    mixed indention, 4 chars (8 chars replaced by tab)"
                          \ ]
                \ )
    else
        let opt = a:arg
    endif
    if     opt == 0
        return
    elseif opt == 1
        set expandtab
        set tabstop=2
        set shiftwidth=2
        set shiftround
        set smarttab
        set softtabstop=0
    elseif opt == 2
        set expandtab
        set tabstop=4
        set shiftwidth=4
        set shiftround
        set smarttab
        set softtabstop=0
    elseif opt == 3
        set expandtab
        set tabstop=8
        set shiftwidth=4
        set shiftround
        set smarttab
        set softtabstop=0
    elseif opt == 4
        set expandtab
        set tabstop=8
        set shiftwidth=8
        set shiftround
        set smarttab
        set softtabstop=0
    elseif opt == 5
        set noexpandtab
        set tabstop=8
        set shiftwidth=8
        set shiftround
        set smarttab
        set softtabstop=0
    elseif opt == 6
        set noexpandtab
        set tabstop=4
        set shiftwidth=4
        set shiftround
        set smarttab
        set softtabstop=0
    elseif opt == 7
        set noexpandtab
        set tabstop=8
        set shiftwidth=2
        set shiftround
        set smarttab
        set softtabstop=2
    elseif opt == 8
        set noexpandtab
        set tabstop=8
        set shiftwidth=4
        set shiftround
        set smarttab
        set softtabstop=4
    else
        echo "Unknown value: " . opt
    endif
    "}}}
endfunction

function FTStatuslineSet()
    "{{{
    let ret  = ' '
    let ret .= '%<%f '      " filename
    let ret .= '%m '        " modified? [-] if unmodifiable
    let ret .= '%r '        " [RO] if readonly
    let ret .= '%y '        " [filetype-name]
    let ret .= "%{'['.(&fenc!=''?&fenc:&enc).'] ['.&ff.']'}"
                            " ^- display (file)encoding
    let ret .= ' [%b]'      " value of byte under cursor
    if &paste
        let ret .= ' [paste]'
    endif
    let ret .= '%='         " rest right aligned
    let ret .= 'col:%v '    " column
    let ret .= 'l:%l/%L   ' " curline/lines

    return ret
    "}}}
endfunction

function FTTablineSet()
    "{{{

    let pre     = ''
    let cur     = ''
    let post    = ''
    let prelen  = 0
    let curlen  = 0
    let postlen = 0
    let is_post = 0
    let is_sel  = 0
    let is_prev = 0
    let maxlen  = &columns - 3

    for tabnum in range(1, tabpagenr('$'))

        let buflist     = []
        let buflist     = tabpagebuflist(tabnum)

        let add = ''
        let is_prev = 0
        if tabnum == tabpagenr()
            let cur = '%#TabLineSel#'
            let is_sel = 1
        else
            if tabnum == g:last_tab
                let add = '%#TabLinePrev#'
                let is_prev = 1
            endif

            if is_sel > 0
                let is_post = 1
            endif

            let is_sel = 0
        endif

        let add .= '[' . tabnum . ':'
        let addlen = strlen(add)
        if is_sel == 1
            let cur  .= add
            let curlen += addlen
        elseif is_post == 1
            let post .= add
            let postlen += addlen
        else
            let pre  .= add
            let prelen += addlen
        endif

        for winnum in range(1, tabpagewinnr(tabnum, ('$')))

            let buffername  = bufname(buflist[winnum - 1])
            let filename    = fnamemodify(buffername, ':t')

            let add = ''

            if winnum > 1
                if is_sel == 1
                    let add  = '%#TabSeparator#' . '|' . '%#TabLineSel#'
                else
                    let add  = '|'
                endif

                if is_sel == 1
                    let curlen += 1
                elseif is_post == 1
                    let postlen += 1
                else
                    let prelen += 1
                endif
            endif

            if gettabwinvar(tabnum, winnum, '&modified' ) != 0
                if is_sel == 1
                    let add .= '%#TabModded#' . '+' . '%#TabLineSel#'
                else
                    let add  = '+'
                endif

                if is_sel == 1
                    let curlen += 1
                elseif is_post == 1
                    let postlen += 1
                else
                    let prelen += 1
                endif
            endif

            if filename == ''
                let filename = 'noname'
            endif

            if strlen(filename) >= 12
                let add .= filename[0:9] . '..'
                let flen = 12
            else
                let add .= filename
                let flen = strlen(filename)
            endif

            if is_sel == 1
                let cur  .= add
                let curlen += flen
            elseif is_post == 1
                let post .= add
                let postlen += flen
            else
                let pre  .= add
                let prelen += flen
            endif

        endfor

        if is_prev == 1
            let add = ']%#TabLine#'
        else
            let add = ']'
        endif
        if is_sel == 1
            let cur  .= add
            let curlen += 1
        elseif is_post == 1
            let post .= add
            let postlen += 1
        else
            let pre  .= add
            let prelen += 1
        endif

    endfo

    if prelen + curlen + postlen > maxlen
        let cut_one  = ((prelen + curlen + postlen) - maxlen)
        let cut_both = (maxlen - curlen - 6) / 2

        if (prelen + curlen > maxlen/2) && (postlen + curlen > maxlen/2)

            let post = post[0:(cut_both - 1)] . "..."
            let pre = "..." . pre[(prelen - cut_both - 1):-1]

        elseif (prelen + curlen + 3 > maxlen)

            let pre = "..." . pre[(cut_one+3):-1]

        elseif (postlen + curlen + 3 > maxlen)

            let post = post[0:postlen - (cut_one+3)] . "..."

        endif

    endif
    return '%#TabLine#' . pre . cur . '%#TabLine#' . post . '%#TabLineFill#%T'

    "}}}
endfunction

function TabMovePrev()
    "{{{
    let curtab  = tabpagenr()

    if curtab == 1
        tabmove
    else
        exec "tabmove" . (curtab - 2)
    endif
    "}}}
endfunction

function TabMoveNext()
    "{{{
    let curtab  = tabpagenr()
    let lasttab = tabpagenr("$")

    if curtab == lasttab
        exec "tabmove" . 0
    else
        exec "tabmove" . (curtab)
    endif
    "}}}
endfunction

if ($VIM_PLEASE_USE_INDENT =~ '^[0-9][0-9]*$')
    call ChooseIndent($VIM_PLEASE_USE_INDENT)
else
    call ChooseIndent(2)
endif

call ChooseLang('__init__')

"}}}

"" keybindings
"{{{

    " lets define a leader for our normal mode bindings first
let mapleader = 'ö'

    " Make p in Visual mode replace the selected text with the "" register.
vmap p <Esc>:let current_reg = @"<CR>gvdi<C-R>=current_reg<CR><Esc>

    " repeat the last :command
nmap _ @:

    " + and - are completely useless;
nmap - /
nmap + ?

    " make ` easier to get on my keyboard
nmap ä `

    " ~ can be a pain two on deadkeys keyboards
nmap Ä ~

    " move the screen
nmap <Leader>t zt
nmap <Leader>g z.
nmap <Leader>b zb

    " jumping to tags
nmap <Leader><C-]>
nmap <Leader><C-T>

    " mapping <- -> ^ v to folding actions; real vi users use hjkl anyway :)
nmap <left>    zc
nmap <right>   zo
nmap <up>      zk
nmap <down>    zj

" function keys

    " 1st, disable F1's help functionality, once and for all
map  <F1> <Esc>
imap <F1> <Esc>
vmap <F1> <Esc>

nmap <silent> <F1> :nohlsearch<CR>
" pastetoggle:
"   to get our statusline to update in insert and normal mode, we to set
"   pastetoggle and the normal mode bind to the :set command.
set  pastetoggle=<F2>
nmap <silent> <F2> :set invpaste<CR>
nmap <silent> <F3> :call ChooseIndent('__interactive__')<CR>
nmap <silent> <F4> :call ChooseLang('__interactive__')<CR>
nmap <silent> <F5> :set invspell<CR>
nmap <silent> <F6> :tabs<CR>
nmap <silent> <F7> :call FTToggleColor()<CR>
nmap <silent> <F8> :set cursorline!<CR>

    " update Last-Modified header of zblog posting
nnoremap <F9>  :let x_lastmod = system("zblog genlastmod")<CR>:execute '/^Last-Modified:/s/\(Last-Modified:\) .*$/\1 ' . x_lastmod . '/'<CR>

    " tab moving
map  <silent> <Leader>h :call TabMovePrev()<CR>
map  <silent> <Leader>l :call TabMoveNext()<CR>

    " turn listchars use on/off
map  <silent> <Leader>L :set invlist<CR>

" SPELL CORRECTION KEYBINDINGS
" remap [s and ]s, which suck on german kerboards
" okay, i just figured out that typing z= sucks aswell.
"   other useful spellcorrection bindings:
"     + zg
"     + zw
"     + zug
"     + zuw
map   <Leader>p        [s
map   <Leader>n        ]s
map   <Leader>c        z=

" switch between the 2 last visited tab pages
autocmd TabLeave * let g:last_tab = tabpagenr()
nmap gS :execute 'normal '.g:last_tab.'gt'<CR>

imap <C-x>i (void)
imap <C-d> <ESC>

"}}}