" ============================================================================= " Miller Medeiros .vimrc file " ----------------------------------------------------------------------------- " heavily inspired by: @factorylabs, @scrooloose, @nvie, @gf3, @bit-theory. " ============================================================================= " ----------------------------------------------------------------------------- " BEHAVIOR " ----------------------------------------------------------------------------- set nocompatible " Disable vi compatibility filetype on " filetype must be 'on' before setting it 'off' " otherwise it exits with a bad status and breaks " git commit. filetype off " force reloading *after* pathogen loaded " set the runtime path to include Vundle and initialize set rtp+=~/.vim/bundle/Vundle.vim call vundle#begin() " let Vundle manage Vundle, required Plugin 'VundleVim/Vundle.vim' Plugin 'wincent/Command-T' Plugin 'vim-scripts/IndentAnything' Plugin 'vim-scripts/IndexedSearch' Plugin 'vim-scripts/LustyJuggler' Plugin 'gregsexton/MatchTag' Plugin 'vim-scripts/YankRing.vim' Plugin 'mileszs/ack.vim' Plugin 'vim-scripts/bufkill.vim' Plugin 'editorconfig/editorconfig-vim' Plugin 'sjl/gundo.vim' Plugin 'sjl/clam.vim' Plugin 'othree/html5.vim' Plugin 'scrooloose/nerdcommenter' Plugin 'scrooloose/nerdtree' Plugin 'junkblocker/patchreview-vim' Plugin 'ervandew/supertab' Plugin 'scrooloose/syntastic' Plugin 'godlygeek/tabular' Plugin 'Lokaltog/vim-easymotion' Plugin 'tpope/vim-repeat' Plugin 'tpope/vim-abolish' Plugin 'tpope/vim-fugitive' Plugin 'tpope/vim-markdown' Plugin 'tpope/vim-speeddating' Plugin 'tpope/vim-surround' Plugin 'tpope/vim-unimpaired' Plugin 'mhinz/vim-signify' Plugin 'int3/vim-extradite' " css Plugin 'ap/vim-css-color' Plugin 'hail2u/vim-css3-syntax' " js Plugin 'pangloss/vim-javascript' Plugin 'elzr/vim-json' Plugin 'mxw/vim-jsx' Plugin 'millermedeiros/vim-esformatter' " Bundle 'marijnh/tern_for_vim' " snipmate Plugin 'MarcWeber/vim-addon-mw-utils' Plugin 'tomtom/tlib_vim' Plugin 'garbas/vim-snipmate' Plugin 'honza/vim-snippets' Plugin 'millermedeiros/vim-statline' " Plugin 'bling/vim-airline' " colorschemes Plugin 'tomasr/molokai' " required for vundle call vundle#end() syntax on filetype plugin indent on " enable detection, plugins and indent " Local dirs (centralize everything) set backupdir=~/.vim/backups set directory=~/.vim/swaps " Change mapleader (easier to type), at the top since its used everywhere let mapleader="," let maplocalleader=";" set spelllang=en_us " spell checking set encoding=utf-8 nobomb " BOM often causes trouble, UTF-8 is awsum. " --- performance / buffer --- set hidden " can put buffer to the background without writing " to disk, will remember history/marks. set lazyredraw " don't update the display while executing macros set ttyfast " Send more characters at a given time. " --- history / file handling --- set history=999 " Increase history (default = 20) set undolevels=999 " Moar undo (default=100) set autoread " reload files if changed externally " --- backup and swap files --- " I save all the time, those are annoying and unnecessary... set nobackup set nowritebackup set noswapfile " --- search / regexp --- set gdefault " RegExp global by default set magic " Enable extended regexes. set hlsearch " highlight searches set incsearch " show the `best match so far' astyped set ignorecase smartcase " make searches case-insensitive, unless they " contain upper-case letters " --- keys --- set backspace=indent,eol,start " allow backspacing over everything. set esckeys " Allow cursor keys in insert mode. set nostartofline " Make j/k respect the columns " set virtualedit=all " allow the cursor to go in to 'invalid' places set timeoutlen=500 " how long it wait for mapped commands set ttimeoutlen=100 " faster timeout for escape key and others " Use a bar-shaped cursor for insert mode, even through tmux. if exists('$TMUX') let &t_SI = "\Ptmux;\\]50;CursorShape=1\x7\\\" let &t_EI = "\Ptmux;\\]50;CursorShape=0\x7\\\" else let &t_SI = "\]50;CursorShape=1\x7" let &t_EI = "\]50;CursorShape=0\x7" endif " ----------------------------------------------------------------------------- " UI " ----------------------------------------------------------------------------- set t_Co=256 " 256 colors terminal let g:molokai_original=0 colorscheme molokai " make 'var' keyword easier to spot hi link javascriptType Keyword " default ColorColumn is too distractive hi clear ColorColumn hi link ColorColumn FoldColumn " defaul line number is too distractive hi clear LineNr hi link LineNr Comment hi link OverLength Error " --- UI settings --- if has('gui_running') "set guifont=Menlo:h13 set gfn:Monaco:h14 set transp=0 " toolbar and scrollbars set guioptions-=T " remove toolbar set guioptions-=L " left scroll bar set guioptions-=r " right scroll bar set guioptions-=b " bottom scroll bar set guioptions-=h " only calculate bottom scroll size of current line set shortmess=atI " Don't show the intro message at start and " truncate msgs (avoid press ENTER msgs). endif set cursorline " Highlight current line set laststatus=2 " Always show status line set number " Enable line numbers. set numberwidth=5 " width of numbers line (default on gvim is 4) set report=0 " Show all changes. set showmode " Show the current mode. set showcmd " show partial command on last line of screen. set showmatch " show matching parenthesis set splitbelow splitright " how to split new windows. set title " Show the filename in the window title bar. set scrolloff=5 " Start scrolling n lines before horizontal " border of window. set sidescrolloff=7 " Start scrolling n chars before end of screen. set sidescroll=1 " The minimal number of columns to scroll " horizontally. " add useful stuff to title bar (file name, flags, cwd) " based on @factorylabs if has('title') && (has('gui_running') || &title) set titlestring= set titlestring+=%f set titlestring+=%h%m%r%w set titlestring+=\ -\ %{v:progname} set titlestring+=\ -\ %{substitute(getcwd(),\ $HOME,\ '~',\ '')} endif " use relative line number by default if exists('+relativenumber') set relativenumber endif " --- command completion --- set wildmenu " Hitting TAB in command mode will set wildchar= " show possible completions. set wildmode=list:longest set wildignore+=*.DS_STORE,*.db,node_modules/**,*.jpg,*.png,*.gif " --- diff --- set diffopt=filler " Add vertical spaces to keep right " and left aligned. set diffopt+=iwhite " Ignore whitespace changes. " --- folding--- set foldmethod=manual " manual fold set foldnestmax=3 " deepest fold is 3 levels set nofoldenable " don't fold by default " --- list chars --- " list spaces and tabs to avoid trailing spaces and mixed indentation " see key mapping at the end of file to toggle `list` set listchars=tab:▹\ ,trail:·,nbsp:⚋ set fillchars=fold:- set list " --- remove sounds effects --- set noerrorbells set visualbell " ----------------------------------------------------------------------------- " INDENTATION AND TEXT-WRAP " ----------------------------------------------------------------------------- set expandtab " Expand tabs to spaces set autoindent smartindent " auto/smart indent set copyindent " copy previous indentation on auto indent set softtabstop=2 " Tab key results in # spaces set tabstop=2 " Tab is # spaces set shiftwidth=2 " The # of spaces for indenting. set smarttab " At start of line, inserts shift width " spaces, deletes shift width spaces. set wrap " wrap lines set textwidth=80 "set colorcolumn=+1 " Show large lines set formatoptions=qrn1 " automatic formating. set formatoptions-=o " don't start new lines w/ comment leader on " pressing 'o' set nomodeline " don't use modeline (security) set pastetoggle=p " paste mode: avoid auto indent, treat chars " as literal. " ----------------------------------------------------------------------------- " PLUGINS " ----------------------------------------------------------------------------- " --- NERDTree ---- let NERDTreeIgnore=['.DS_Store'] let NERDTreeShowBookmarks=0 "show bookmarks on startup let NERDTreeHighlightCursorline=1 "Highlight the selected entry in the tree let NERDTreeShowLineNumbers=0 let NERDTreeMinimalUI=1 noremap nt :NERDTreeToggle " --- NERDCommenter --- let NERDSpaceDelims=1 " space around delimiters let NERDRemoveExtraSpaces=1 let g:NERDCustomDelimiters = { \ 'scss': { 'left': '//' } \ } " --- Syntastic : Linting / Error check --- let g:syntastic_auto_loc_list=2 let g:syntastic_check_on_open=1 " close/open location list (errors) noremap lc :lcl noremap lo :Errors :lw noremap ln :lnext noremap lp :lprev " --- autocomplete / supertab / jscomplete --- set infercase set completeopt=longest,menuone set omnifunc=syntaxcomplete#Complete set completefunc=syntaxcomplete#Complete set complete=.,w,b,u,U,t,i,d " see [autocommands] at the end for more autocomplete settings " nodejs-complete / jscomplete let g:node_usejscomplete = 1 let g:jscomplete_use = ['dom', 'moz'] let g:SuperTabMappingForward = '' let g:SuperTabMappingBackward = '' let g:SuperTabLongestEnhanced = 1 let g:SuperTabDefaultCompletionType = "" " --- snipmate --- let g:snips_author = 'Miller Medeiros' " --- EasyMotion --- let g:EasyMotion_leader_key = 'm' " lets make F and f use easymotion by default let g:EasyMotion_mapping_f = 'f' let g:EasyMotion_mapping_F = 'F' " --- Strip trailing whitespace --- function! StripWhitespace () let save_cursor = getpos(".") let old_query = getreg('/') :%s/\s\+$//e call setpos('.', save_cursor) call setreg('/', old_query) endfunction " Trailing white space (strip spaces) noremap ss :call StripWhitespace() " --- matchit --- runtime macros/matchit.vim " enable matchit (better '%' key mapping) " --- vim-css-color --- let g:cssColorVimDoNotMessMyUpdatetime = 1 " --- vim-signify --- let g:signify_update_on_focusgained = 1 " --- Command-T --- let g:CommandTMaxFiles=2000 let g:CommandTMaxHeight=12 noremap tt :CommandT noremap bt :CommandTBuffer noremap tf :CommandTFlush " --- LustyJuggler --- let g:LustyJugglerSuppressRubyWarning = 1 " avoid error if running on terminal " --- statline --- " errors color hi User3 guifg=#FFFFFF guibg=#FF0000 gui=bold ctermfg=15 ctermbg=1 cterm=bold let g:statline_fugitive = 1 let g:statline_filename_relative = 1 let g:statline_mixed_indent_string = '[mix]' " --- gundo --- nnoremap gu :GundoToggle let g:gundo_right = 1 let g:gundo_preview_bottom = 1 " --- toggle indentation mode --- function! ToggleExpandTab() if &et set noet softtabstop=0 else execute "set et softtabstop=". &tabstop endif endfunction noremap et :call ToggleExpandTab() " --- Show syntax highlighting groups for word under cursor --- " http://vimcasts.org/episodes/creating-colorschemes-for-vim/ nnoremap sh :call SynStack() function! SynStack() if !exists("*synstack") return endif echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")') endfunc " faster wehn opening files with large lines set synmaxcol=300 " --- Highlight word under cursor --- " hi W1 guibg=#aeee00 guifg=#000000 ctermbg=154 ctermfg=16 " nnoremap h1 :execute 'match W1 /\<\>/' " --- Tabular.vim --- noremap t: :Tabularize /: noremap t= :Tabularize /= noremap t, :Tabularize /, noremap t{ :Tabularize /{ noremap t" :Tabularize /" noremap t' :Tabularize /' noremap t[ :Tabularize /[ noremap t/ :Tabularize /// noremap t\| :Tabularize /\| " --- include content of static files --- " borrowed from: http://vim.1045645.n5.nabble.com/vim-counterpart-for-persistent-includes-td4276915.html function! IncludeStatic() :g/\_.\{-}/let fname = matchstr(getline('.'),'')|exec '+,//-!cat '.fnameescape(fname) endfunction noremap ic :call IncludeStatic() " --- convert selected text from markdown to HTML --- vnoremap md :! mdown function! SanitizeMdown() %s/<\/\?p>// %s/
/ / %s/
/
\r/
    %s/<\/code><\/pre>/<\/pre>/
endfunc
noremap  mds :call SanitizeMdown()



" --- format JavaScript source code using esformatter --

nnoremap  es :Esformatter
vnoremap  es :EsformatterVisual



" --- toggle autocomplete behavior and word delimiters ---

function! KeywordsAll()
    setl iskeyword=@,48-57,192-255,\@,\$,%,-,_
endfunc

function! KeywordsBasic()
    setl iskeyword=@,48-57,192-255
endfunc


" --- visual block move ---
" http://www.youtube.com/watch?v=aHm36-na4-4#t=35m10

let g:DVB_TrimWS = 1
vmap       DVB_Drag('left')
vmap      DVB_Drag('right')
vmap       DVB_Drag('down')
vmap         DVB_Drag('up')
vmap    D        DVB_Duplicate()


" --- transform lists ---
" http://www.youtube.com/watch?v=aHm36-na4-4#t=17m30

nmap ls :call ListTrans_toggle_format()
vmap ls :call ListTrans_toggle_format('visual')



" -----------------------------------------------------------------------------
" KEY MAPPINGS
" -----------------------------------------------------------------------------

" mapleader set at the top of the file to avoid conflicts


" --- FIX/IMPROVE DEFAULT BEHAVIOR ---

" faster commands
" nnoremap  :

" sudo write
" command! W w !sudo tee % > /dev/null

" Swap v and CTRL-V, because Block mode is more useful that Visual mode
" nnoremap    v   
" nnoremap      v
" vnoremap    v   
" vnoremap      v

" avoid mistyping commands
command! W w
command! Wq wq
command! Bd bd

" Split line (sister to [J]oin lines)
" The normal use of S is covered by cc, so don't worry about shadowing
nnoremap S i

" movement by screen line instead of file line (for text wrap)
nnoremap j gj
nnoremap  gj
nnoremap k gk
nnoremap  gk

" next tab
nnoremap  :tabn

" automatic esc, really uncommon to type jj,jk
inoremap jj 
inoremap jk 

" Faster scrolling
nnoremap  3
nnoremap  3

" Bubble single lines, similar to Eclipse (requires unimpaired.vim)
nmap  [e
nmap  ]e

" Bubble multiple lines, similar to Eclipse (requires unimpaired.vim)
vmap  [egv
vmap  ]egv

" Duplicate lines, similar to Eclipse
noremap  YP
noremap  YP

" 'fix' search regexp to be compatible with Perl format
" nmap / /\v
" vmap / /\v

" Use the damn hjkl keys
" noremap  
" noremap  
" noremap  
" noremap  

" improve the 'search word under cursor' behavior
nnoremap * :silent call KeywordsAll() *
nnoremap # :silent call KeywordsAll() #


" --- COMMON STUFF / HELPERS ---

" Toggle show tabs and trailing spaces
nnoremap c :set nolist!

" Clear the search highlight
nnoremap  \ :silent nohlsearch

" text wrap: Hard wrap paragraph text (similar to TextMate Ctrl+Q)
nnoremap tw gqip
nnoremap nw :set nowrap

" Open file (useful for HTML)
noremap  o :!open %

" Reformat code
nnoremap rf gg=G

" I use retab too much and it's hard to type
nnoremap rt :retab!

" Pull word under cursor into LHS of a substitute (find and replace)
nnoremap rr :silent call KeywordsAll() :%s#\<=expand("")\>#

" Insert/append a single character
" noremap ,, i_r
" noremap ;; a_r

" Visually select the text that was last edited/pasted
nnoremap v `[v`]

" fast Ack
nnoremap a :tab split:Ack
nnoremap aw :silent call KeywordsAll() :tab split:Ack :silent call KeywordsBasic()

" Toggle spelling hints
nnoremap  ts :set spell!


" Move between splits (windows)
noremap  h
noremap  j
noremap  k
noremap  l

" Move windows around (only works on same row)
noremap  r
noremap  R

" Open current buffer in a new split
noremap s :vsplit
noremap i :split

" close window
noremap q :clo

" delete buffer but keep window open (requires bufkill.vim)
map bd :BD

" smarter next/prev buffer (requires bufkill.vim)
map bn :BF
map bp :BB

" resize splits (http://vim.wikia.com/wiki/Resize_splits_more_quickly)
nnoremap  + :exe "resize " . (winheight(0) * 3/2)
nnoremap  - :exe "resize " . (winheight(0) * 2/3)


" add spaces inside current parenthesis
map ( vi(xi  P



" -----------------------------------------------------------------------------
" FILE HANDLING
" -----------------------------------------------------------------------------

" [autocommands] borrowed from @bit-theory vimfiles and edited
augroup mm_buf_cmds
    " clear commands before resetting
    autocmd!

    " when vimrc is edited, reload it
    autocmd bufwritepost .gvimrc source %
    autocmd bufwritepost .vimrc source %

    " Only show cursorline in the current window and in normal mode
    au WinLeave,InsertEnter * set nocul
    au WinEnter,InsertLeave * set cul

    " filetype
    autocmd BufNewFile,BufRead *.json setf json
    autocmd BufNewFile,BufRead *.hx setf haxe

    autocmd FileType mustache runtime! ftplugin/html/sparkup.vim

    " Enable omnicomplete for supported filetypes
    autocmd FileType css,scss setlocal omnifunc=csscomplete#CompleteCSS
    autocmd FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
    " autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
    " jscomplete is a separate plugin
    autocmd FileType javascript setlocal omnifunc=jscomplete#CompleteJS
    autocmd FileType python setlocal omnifunc=pythoncomplete#Complete
    autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags

    " make `gf` search for .js files
    autocmd FileType javascript setlocal suffixesadd=.js
    autocmd FileType javascript setlocal path+=js,scripts


    " make sure `complete` works as expected for CSS class names without
    " messing with motions (eg. '.foo-bar__baz') and we make sure all
    " delimiters (_,-,$,%,.) are treated as word separators outside insert mode
    autocmd InsertEnter,BufLeave * :silent call KeywordsAll()
    autocmd InsertLeave,BufEnter * :silent call KeywordsBasic()

    " yes, we need to duplicate it on VimEnter for some weird reason
    autocmd VimEnter * nnoremap * :silent call KeywordsAll() *
    autocmd VimEnter * nnoremap # :silent call KeywordsAll() #


    " Toggle relative/absolute line numbers during edit
    " if exists('+relativenumber')
        " autocmd InsertEnter * setl nu
        " autocmd InsertLeave,BufEnter * setl rnu
    " endif

    " highlight char at column 81 (textwidth + 1)
    autocmd BufEnter * match OverLength /\%81v/

    " Color Column (only on insert)
    if exists("&colorcolumn")
        autocmd InsertEnter * set colorcolumn=80
        autocmd InsertLeave * set colorcolumn=""
    endif
augroup END