view vim/vimrc @ 306:7a47a1cc8687

Why the fuck was I doing that.
author Ludovic Chabant <ludovic@chabant.com>
date Wed, 29 Jul 2015 00:48:02 -0700
parents a333541a5c74
children b09d451f3516
line wrap: on
line source

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"
" Ludovic Chabant's ~/.vimrc
"
" http://ludovic.chabant.com
"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" Global Setup {{{

" Use Vim settings, rather then Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible

" Set a variable that says we already sourced this file, for those few
" settings we don't want to re-apply.
if exists('g:sourced_vimrc')
    let g:resourcing_vimrc = 1
endif
let g:sourced_vimrc = 1

" Get the platform we're running on.
if has("win32") || has("win64") || has("dos32")
    let s:vim_platform = "windows"
    let s:path_sep = "\\"
else
    let s:vim_platform = "unix"
    let s:path_sep = '/'
endif

" Get our vim directory. 
let s:vim_home = expand("<sfile>:h")

" Make sure `filetype` stuff is turned off before loading Pathogen.
syntax off
filetype off

" Disable some plugins.
let g:pathogen_disabled = []
call add(g:pathogen_disabled, 'vimroom')
call add(g:pathogen_disabled, 'minibufexpl')
call add(g:pathogen_disabled, 'ragtag')

" Potentially add the local bundle directory.
if isdirectory(s:vim_home.s:path_sep.'local')
    execute 'set runtimepath+='.s:vim_home.s:path_sep.'local'
endif

" Load pathogen.
"call pathogen#infect()
call pathogen#runtime_append_all_bundles()

" Hide the toolbar in MacVim/gVIM, and set a nice window size.
if has("gui_running") && !exists('g:resourcing_vimrc')
    set guioptions=-t
    set lines=999
    set columns=999
endif

" }}}

" General Settings {{{

" Restrict modelines.
set modelines=1

" Don't unload abandoned buffers.
set hidden

" Show line numbers.
set number

" Show what mode we're in, and what command we're typing.
set showmode
set showcmd

" Keep the cursor off the top/bottom edges.
set scrolloff=3

" Smart auto-indenting.
set autoindent
set smartindent

" Use confirmation dialog.
set confirm

" Don't use annoying sounds.
set visualbell

" Remember lots of commands.
set history=1000

" Try to reduce flickering.
set lazyredraw

" Show matching braces but not for too long.
set showmatch
set matchtime=2

" Show soft-broken/wrapped lines with a prefix.
set showbreak=→

" Use incremental search, with highlighting,
" case-insensitive unless we actually type some
" mixed-case stuff.
set incsearch
set hlsearch
set ignorecase
set smartcase

" Always show window status lines.
set laststatus=2

" Enable using the mouse like some everyday guy.
set mouse=a

" Show interesting stuff at the bottom of the window.
set showcmd
set ruler

" Make sure splitting windows is done in a way that makes sense.
set splitbelow
set splitright

" Don't pollute the hard-drive with *~ files. Only
" create them in hidden backup/temp directories while
" we edit the file, and then get rid of it.
set nobackup
set writebackup
execute('set backupdir='.s:vim_home.'/backup')
execute('set directory='.s:vim_home.'/temp')

" Better command-line completion, but don't show some
" stuff we don't care about.
set wildmenu
set wildignore+=.DS_Store,Thumbs.db,*.so,*.dll,*.exe,*.lib,*.pdb,*.pyc,*.pyo

" Always display the tab-page line.
set showtabline=2

" Set the file-formats.
set ffs=unix,mac,dos

" Tabs and indenting are 4 characters, and tabs behave like
" spaces during editing. They're smart, too, and when you
" press <TAB> it actually inserts a soft-tab so everything's
" indented the same.
set tabstop=4
set shiftwidth=4
set softtabstop=4
set smarttab
set expandtab

" Default encoding
set encoding=utf-8

" Clipboard buffer.
set clipboard=unnamed

" Smoot terminal experience.
set ttyfast

" Allow backspacing over anything.
set backspace=indent,eol,start

" Going left and right let you go to other lines.
set whichwrap+=<,>,h,l

" How to show invisible characters
set listchars=eol:$,tab:>-,trail:-,extends:>,precedes:<,nbsp:%,conceal:.

" Nice auto-complete menu.
set completeopt=longest,menuone,preview

" Column indicators.
set colorcolumn=72,79

" And now, for some system-dependent settings:
" - font to use
if s:vim_platform == "windows"
    set guifont=Consolas:h12
else
    set guifont=Monaco:h12
endif

" Syntax highlighting.
syntax on

" Change the current directory to the home directory.
if !exists('g:resourcing_vimrc')
    cd ~/
endif

" Default color scheme.
if has('gui_running')
    set background=dark
else
    set background=dark
    "let g:solarized_termcolors = 256
    "let g:solarized_termtrans = 1
endif
colorscheme solarized

" Enable file type detection.
filetype indent plugin on

" }}}

" Auto-Commands {{{

" Only show the highlighted cursor line in the current window.
augroup CursorLine
    au!
    au WinLeave * set nocursorline
    au WinEnter * set cursorline
augroup END

" }}}

" Plugin Settings {{{

" Ctrl-P {{{

" We'll set our own mappings.
let g:ctrlp_map = ''

" Ctrl-P should manage the working directory.
let g:ctrlp_working_path_mode = 'ra'

" Ctrl-P should however ignore some stuff.
let g:ctrlp_custom_ignore = {
  \ 'dir':  '\v[\/](\.git|\.hg|\.svn|venv|static|node_modules|_cache|_counter)$'
  \ }

" Make Ctrl-P cache stuff in our temp directory.
let g:ctrlp_cache_dir = s:vim_home.'/cache'

" Remember things.
let g:ctrlp_clear_cache_on_ext = 0

" Enable some cool extensions.
let g:ctrlp_extensions = [
            \'tag', 'buffertag', 'quickfix', 'mixed', 'bookmarkdir',
            \'autoignore'
            \]

" }}}

" Gutentags {{{

let g:gutentags_exclude = ['venv', 'build', 'static', 'node_modules']
let g:gutentags_cache_dir = s:vim_home.'/tags'
let g:gutentags_options_file = s:vim_home.'/ctagsrc'

" }}}

" Syntastic {{{

let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0

" flake8 includes pyflakes, pep8, and mccabe
" I could maybe replace pyflakes with frosted?
let g:syntastic_python_checkers = ['flake8'] ", 'pylint']
let g:syntastic_python_python_exec = 'python3'

" }}}

" Supertab {{{

let g:SuperTabDefaultCompletionType = "<c-n>"
let g:SuperTabLongestHighlight = 1
let g:SuperTabCrMapping = 1

" }}}

" Lawrencium {{{

" Custom Mercurial commands highlighting in Lawrencium.
let g:lawrencium_hg_commands_file_types = {
            \'clog': 'hggraphlog'
            \}

" Make the annotate window better in Lawrencium.
let g:lawrencium_annotate_width_offset = 1

" }}}

" Gundo {{{

let g:gundo_map_move_older = '<Down>'
let g:gundo_map_move_newer = '<Up>'

" }}}

" YankRing {{{

let g:yankring_replace_n_pkey = '<C-K>'
let g:yankring_replace_p_pkey = '<C-J>'

" }}}

" Python-Mode {{{

let g:pymode = 1
let g:pymode_python = 'disable'
let g:pymode_syntax_all = 1
let g:pymode_syntax_print_as_function = 1
let g:pymode_syntax_space_errors = 1
let g:pymode_run = 0
let g:pymode_lint = 0
let g:pymode_trim_whitespaces = 0
let g:pymode_virtualenv = 0
let g:pymode_folding = 1

if !has('+python')
    let g:pymode = 0
endif

" }}}

" }}}

" File-Specific Settings {{{

" Automatically change the current working directory based on a project
" I'm in.
augroup VimRCAutoCWD
    au!
    autocmd BufReadPost * call s:SetProjectRootCwd(1)
    autocmd BufEnter * call s:SetProjectRootCwd(0)
augroup END

augroup VimRCFileType_markdown
    au!
    autocmd FileType text,markdown setlocal textwidth=80
    autocmd FileType markdown nnoremap <buffer> <localleader>1 yypVr=:redraw<cr>
    autocmd FileType markdown nnoremap <buffer> <localleader>2 yypVr-:redraw<cr>
    autocmd FileType markdown nnoremap <buffer> <localleader>3 mzI###<space><esc>`z4l
    autocmd FileType markdown nnoremap <buffer> <localleader>4 mzI####<space><esc>`z5l

    autocmd BufRead,BufNewfile */Dropbox/Personal/SimpleNote/* set ft=markdown
    autocmd BufRead,BufNewFile */_content/**/*.html set ft=piecrustmarkdown
augroup END

augroup VimRCFileType_php
    au!
    " Who the hell changes my matchpairs?
    autocmd FileType php setlocal matchpairs-=<:>
augroup END

augroup VimRCFileType_c
    au!
    autocmd FileType c,c++,cpp setlocal foldmethod=syntax
augroup END

augroup VimRCFileType_css
    au!
    autocmd BufNewFile,BufRead *.less setlocal filetype=less
    autocmd Filetype less,css setlocal foldmethod=marker
    autocmd Filetype less,css setlocal foldmarker={,}
    autocmd Filetype less,css setlocal iskeyword+=-
    autocmd Filetype less,css setlocal omnifunc=csscomplete#CompleteCSS
augroup END

augroup VimRCFileType_python
    au!
    autocmd FileType python setlocal define=\\v^\\s*(def\|class)\\s+
    "autocmd FileType python if exists('python_space_error_highlight')|unlet python_space_error_highlight|endif
augroup END

augroup VimRCTrailingWhitespaces
    au!
    autocmd FileType php,ruby,python,js,css,less autocmd BufWritePre <buffer> :call <SID>StripTrailingWhitespaces()
augroup END       

" }}}

" Mappings {{{

let mapleader=","

" Visual line navigation
noremap <up> g<up>
noremap <down> g<down>
noremap <home> g<home>
noremap <end> g<end>

" Tab navigation
noremap <C-Tab>   :tabnext<cr>
noremap <C-S-Tab> :tabprevious<cr>
nnoremap <leader>t :tabnew<cr>

" Window navigation
nnoremap <C-up> :wincmd k<cr>
nnoremap <C-down> :wincmd j<cr>
nnoremap <C-left> :wincmd h<cr>
nnoremap <C-right> :wincmd l<cr>

" Switch buffers.
nnoremap <F2> :execute ("buffer " . bufname("#"))<cr>

" NERDTree.
nnoremap <F3> :call <SID>ToggleNERDTree()<cr>
nnoremap <F4> :call <SID>FindInNERDTree()<cr>

" Tagbar.
nnoremap <F5> :TagbarToggle<cr>
nnoremap <F6> :TagbarOpenAutoClose<cr>

" Gundo.
nnoremap <F7> :GundoToggle<cr>

" Common typos.
nnoremap ; :

" Split windows
nnoremap <leader>s :split<cr>
nnoremap <leader>v :vsplit<cr>

" Easier things to type
nnoremap <leader>w :w<cr>
nnoremap <leader>q :q<cr>
nnoremap <leader>hh :Hg 
nnoremap <leader>hg :Hg! 
nnoremap <leader>hs :Hgstatus<cr>
nnoremap <leader>hv :Hgvdiff<cr>

" Make the hash-key not suck.
inoremap # X<BS>#

" Toggle invisible characters
nnoremap <leader>i :set list!<cr>

" Clear search matches
nnoremap <leader><space> :noh<cr>:call clearmatches()<cr>

" Ctrl-P mappings.
nnoremap <silent> <C-p> :CtrlP<cr>
nnoremap <silent> <C-o> :CtrlPBuffer<cr>
nnoremap <silent> <C-u> :CtrlPTag<cr>
nnoremap <silent> <C-y> :CtrlPQuickfix<cr>
nnoremap <silent> <Tab> :CtrlPMRUFiles<cr>
nnoremap <silent> <F8> :CtrlPBookmarkDir<cr>

" Switch between FR and US keyboard layouts.
nnoremap <C-l>f :setlocal keymap=french<cr>
nnoremap <C-l>u :setlocal keymap=<cr>

" Toggle spell check according to current keyboard layout.
nnoremap <C-l>s :call <SID>ToggleSpellCheck()<cr>

" Simple way to close a buffer without closing the window.
nnoremap <leader>bd :bprevious<cr>:bdelete #<cr>

" Use sane regexes.
nnoremap / /\v
vnoremap / /\v

" Next/previous quickfix and location messages.
" This is meant to be similar to ]c and [c for the diff navigation.
nnoremap ]q :cnext<cr>zvzz
nnoremap [q :cprevious<cr>zvzz
nnoremap ]l :lnext<cr>zvzz
nnoremap [l :lprevious<cr>zvzz

" Same with change and jump lists.
nnoremap ]] g,zz
nnoremap [[ g;zz
nnoremap ]j <C-I>
nnoremap [j <C-O>

" Make the diff navigation also center things.
nnoremap ]c ]czvzz
nnoremap [c [czvzz

" Quick search and replace.
function! s:VSetSearch()
    let temp = @@
    norm! gvy
    let @/ = '\V' . substitute(escape(@@, '\'), '\n', '\\n', 'g')
    let @@ = temp
endfunction
vnoremap * :<C-u>call <SID>VSetSearch()<CR>//<CR><c-o>
vnoremap # :<C-u>call <SID>VSetSearch()<CR>??<CR><c-o>

nnoremap <leader>fa :vimgrep /<C-R><C-W>/ 
vnoremap <leader>fa "zy:vimgrep /<C-R>z/ 

" Jump to tags by keeping things better in view. Option for jumping to a tag
" in a split window where everything is folded except what you need to see.
" Note that if a tag search yield multiple possible results, we will still run
" some of that `zvzz` stuff, but that's OK, the main point is to not mess up
" the result selection window either.
nnoremap <c-]> <c-]>zvzz
nnoremap <c-[> :pop<cr>
nnoremap <c-\> <c-w>v<c-]>zMzvzz
nnoremap <F9>  :tprevious
nnoremap <F10> :tnext

" Keep search matches in the middle of the window.
nnoremap n nzvzz
nnoremap N Nzvzz

" }}}

" Folding {{{

" Folds are defined by markers in the text.
set foldmethod=marker

" Toggle folds with <space>.
nnoremap <space> za

" Create folds with <space> (in visual mode).
vnoremap <space> zf

" }}}

" Abbreviations {{{

iabbrev @@      ludovic@chabant.com
iabbrev ccopy   Copyright &copy;2011 Ludovic Chabant, all rights reserved.
iabbrev ssig    --<cr>l u d o .<cr>. 8 0 17 80

" }}}

" Status Line {{{

set statusline=%f    " Path.
set statusline+=%m   " Modified flag.
set statusline+=%r   " Readonly flag.
set statusline+=%w   " Preview window flag.

set statusline+=\    " Space.

set statusline+=%#redbar#                       " Highlight the following as a warning.
set statusline+=%{SyntasticStatuslineFlag()}    " Syntastic errors.
set statusline+=%*                              " Reset highlighting.

set statusline+=%=   " Right align.

" Tag file generation indicator.
set statusline+=%{gutentags#statusline('[TAGS]')}
set statusline+=\    " Space.

" Mercurial information.
set statusline+=%{lawrencium#statusline('[',']')}
set statusline+=\    " Space.

" File format, encoding and type.  Ex: "(unix/utf-8/python)"
set statusline+=(
set statusline+=%{&ff}                        " Format (unix/DOS).
set statusline+=/
set statusline+=%{strlen(&fenc)?&fenc:&enc}   " Encoding (utf-8).
set statusline+=/
set statusline+=%{&ft}                        " Type (python).
set statusline+=)

" Line and column position and counts.
set statusline+=\ (%l\/%L,%03c)

" }}}

" Functions {{{

function! s:ToggleSpellCheck() abort
    if &spell ==? 'nospell'
        if &keymap ==? 'french'
            setlocal spell spelllang=fr_fr
        else
            setlocal spell spelllang=en_us,en_ca
        endif
    else
        setlocal spell nospell
    endif
endfunction

function! s:StripTrailingWhitespaces() abort
    let l = line(".")
    let c = col(".")
    %s/\s\+$//e
    call cursor(l, c)
endfunction

function! s:FindProjectRoot(cur, marker) abort
    let l:cur = a:cur
    let l:previous_cur = ''
    let l:slash = '/'
    if has('win32')
        let l:slash = '\'
    endif
    while l:cur != l:previous_cur
        let l:marker_path = l:cur . l:slash . a:marker
        if glob(l:marker_path) != ''
            return fnamemodify(l:cur, ':p')
        endif
        let l:previous_cur = l:cur
        let l:cur = fnamemodify(l:cur, ':h')
    endwhile
    return ''
endfunction

function! s:SetProjectRootCwd(recompute) abort
    if a:recompute != 1 && exists('b:ludo_workdir')
        execute 'lcd!' fnameescape(b:ludo_workdir)
        return
    endif

    let l:cur_file_dir = expand('%:p:h', 1)
    if l:cur_file_dir =~ '\v^(\w+:)?(//|\\\\)'
        " Don't do shit on filenames coming from the network or something.
        return
    endif
    let l:found_root = 0
    let l:root = ''
    let l:markers = []
    if exists('g:ctrlp_root_markers')
        let l:markers += g:ctrlp_root_markers
    endif
    let l:markers += ['.git', '.hg', '.svn', '.bzr', '_darcs']
    let l:unique_markers = []
    for marker in l:markers
        if index(l:unique_markers, marker) < 0
            call add(l:unique_markers, marker)
        endif
    endfor
    " Find the project root closest to the current file.
    for marker in l:unique_markers
        let l:proj_root = s:FindProjectRoot(l:cur_file_dir, marker)
        if l:proj_root != '' && len(l:proj_root) > len(l:root)
            let l:root = l:proj_root
            let l:found_root = 1
        endif
    endfor
    if l:found_root
        let b:ludo_workdir = l:root
        execute 'lcd!' fnameescape(l:root)
    endif
endfunction

function! s:ToggleNERDTree() abort
    NERDTreeToggle
endfunction

function! s:FindInNERDTree() abort
    if !g:NERDTree.IsOpen() || getbufvar('%', 'NERDTreeType') == ''
        " If we're not in the NERDTree window, switch to it and find the
        " current file in it.
        NERDTreeFind
        normal zz
    else
        " We're in the NERDTree window, go back to the previous one.
        wincmd p
    endif
endfunction

" }}}

" Local override {{{

let s:local_vimrc = s:vim_home.'/vimrc-local'
if filereadable(s:local_vimrc)
    execute 'source' s:local_vimrc
endif

" }}}