Vim cursor moves forward 7 characters when I use my remapped <Esc> - vim

I took a stab at writing my own .vimrc for the first time. I've gotten used to using "kj" as a replacement for Escape so I added a remapping. Here is a copy of my .vimrc:
set nocompatible
filetype off
" Plugins
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
Plugin 'sjl/badwolf'
Plugin 'scrooloose/nerdtree'
Plugin 'scrooloose/syntastic'
Plugin 'scrooloose/nerdcommenter'
Plugin 'tpope/vim-fugitive'
Plugin 'kien/ctrlp.vim'
Plugin 'majutsushi/tagbar'
Plugin 'bling/vim-airline'
Plugin 'bronson/vim-trailing-whitespace'
call vundle#end()
filetype plugin indent on
" Ctrl P
let g:ctrlp_atch_window = 'bottom,order:ttb'
let g:ctrlp_switch_buffer = 0
let g:ctrlp_working_path_mode = 0
" Syntastic
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0
let g:syntastic_js_checkers = ['jshint']
" Fugitive
set statusline+=%{fugitive#statusline()}
" Vim Airline
set laststatus=2
" Colors
syntax enable
colorscheme badwolf
let g:badwolf_darkgutter=1
" Misc
set ttyfast
set backspace=indent,eol,start
" Spaces & Tabs
set tabstop=2
set expandtab
set softtabstop=2
set shiftwidth=2
set autoindent
" UI Layout
set number
set showcmd
set cursorline
set wildmenu
set showmatch
match Error /\%81v.\+/
" Searching
set ignorecase
set incsearch
set hlsearch
" Folding
" set foldmethod=indent
" set foldnestmax=10
" set foldenable
" nnoremap <space> za
" set foldlevelstart=10
" Shortcut Remmaping
inoremap kj <Esc>
vnoremap kj <Esc>
" Movement
" nnoremap <buffer> <silent> j gj
" nnoremap <buffer> <silent> k gk
map <C-h> :wincmd h<CR>
map <C-j> :wincmd j<CR>
map <C-k> :wincmd k<CR>
map <C-l> :wincmd l<CR>
" Leader Shortcuts
let mapleader=","
let g:mapleader=","
nnoremap <leader>w :NERDTree<CR>
nnoremap <leader>l :call ToggleNumber()<CR>
nnoremap <leader><space> <silent> :nohlsearch<CR>
nnoremap <leader>t :TagbarToggle<CR>
" Custom Functions
function! ToggleNumber()
if(&relativenumber == 1)
set norelativenumber
set number
else
set relativenumber
endif
endfunc
" Return to last edit position when opening files (You want this!)
autocmd BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
" Remember info about open buffers on close
set viminfo^=%
When I include the "kj" remappings upon pressing "kj" while in insert mode, I enter normal mode and then my cursor moves forwards 7 characters. Without the remapping the letters are simply be typed into the buffer.
I have tried disabling all of my plugins, but the problem still persists. This is driving me mad, any ideas what could be causing this to happen?

There are trailing spaces right after inoremap kj <Esc>, which is interpreted as a part of the mapping. Try removing these spaces.

Related

CoC: Diagnostic window takes over screen

I am setting up neovim, with CoC.
It seems to work well, but with one big problem: My diagnostic windows are very large
I am not sure why this is. I would expect this to be only a few lines. Ideally, it should show up somewhere not directly over the code, but I'm not sure how to configure this.
This is my neovim config:
call plug#begin('~/.config/nvim/autoload')
Plug 'easymotion/vim-easymotion' " Get to where you want to go fast
Plug 'nanotech/jellybeans.vim' " Pretty theme
Plug 'scrooloose/nerdtree'
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim' " Fuzzy search
Plug 'jiangmiao/auto-pairs', { 'tag': 'v2.0.0' } " auto-pairs of parens
Plug 'Olical/conjure', {'tag': 'v4.15.0'} " Interactive Clojure Eval
Plug 'guns/vim-sexp' " paredi for vim
Plug 'tpope/vim-sexp-mappings-for-regular-people'
Plug 'clojure-vim/clojure.vim'
Plug 'neoclide/coc.nvim', {'branch': 'release'} " Language servers for vim!
Plug 'w0rp/ale' " linter -- TODO: maybe lsp obviates the need for this?
call plug#end()
" vim:foldmethod=marker:foldlevel=0
" Stopa's vimrc -- my magic sauce for getting things done!
" -----------------------------------------------------------------------------
" Vim settings {{{1
" Important {{{2
set nocompatible " Enable Vim features
syntax on " Turn on syntax highlighting
let mapleader = "," " Set <leader> character
let maplocalleader = "," " Set <localleader> character
colorscheme jellybeans " Favorite so far
set encoding=utf-8 " Use utf-8 when reading files
set fileencoding=utf-8 " Files are written using utf-8
set lazyredraw " Don't redraw on macros -- boosts performance
set ttyfast " Faster redraws and smoother vim
set modelines=1 " Read the modeline at the top
" Ignore these files in Vim's file explorer {{{2
set wildignore+="/tmp/*,*.so,*.swp,*.zip
" Make clipboard the default register {{{2
set clipboard=unnamed
" Highlight column 81 {{{2
set colorcolumn=81
highlight ColorColumn ctermbg=234
" General {{{2
set autoread " Reload files when outside changes made
set backspace=indent,eol,start " Allow backspace in insert mode
set foldnestmax=2 " Sets max fold level.
set gcr=a:blinkon0 " Disable cursor blink
set hidden " Buffers can exist in background
set history=1000 " keep 100 lines of command line history
set laststatus=2 " lightline needs this to display status when opening first buffer
set noshowmode " using Lightline to show status bar instead
set noswapfile " Disable swap files. I don't use them
set number " Line numbers!
set ruler " show the cursor position all the time
set scrolloff=8 " Start scrolling 8 lines away from bottom
set shortmess+=I " Remove Vim startup message for empty file
set showcmd " Show incomplete commands at bottom
set showmode " Show current mode down the bottom
set splitbelow " Default horizontal split below
set splitright " Default vertical split right
set visualbell " Disable sounds
" Wrap {{{2
set wrap
set linebreak " Wrap lines at convienent points
set textwidth=0
set wrapmargin=0
" Searching {{{2
set hlsearch " highlight searching
set incsearch " do incremental searching
set ignorecase " searches are case insensitive
set smartcase " unless you search with a capital letter
" Tabs and Spaces {{{2
set expandtab
set tabstop=4
set softtabstop=4
set shiftwidth=4
" Auto adjust window sizes when they become current {{{2
set winwidth=84
set winheight=5
set winminheight=5
set winheight=999
" }}} End section
" Key mappings {{{1
" Highlight initials in notes {{{2
:match Todo /JA:/
" Easy Navigating {{{2
:inoremap jk <Esc>
:nnoremap j gj
:nnoremap k gk
" Easy window cycling {{{2
:nnoremap <C-h> <C-w>h
:nnoremap <C-j> <C-w>j
:nnoremap <C-k> <C-w>k
:nnoremap <C-l> <C-w>l
" Easy save/quit {{{2
:noremap <leader>w :w<CR>
:nnoremap <leader>q :q!<CR>
:nnoremap <leader>zz :qa!<CR>
" Reload vimrc file {{{2
:nnoremap <silent><leader>sv :so $MYVIMRC<CR>
" Edit useful files {{{2
:nnoremap <silent><leader>ev :e $MYVIMRC<CR>
:nnoremap <silent><leader>et :e $MYTMUXCONF<CR>
:nnoremap <silent><leader>ez :e $MYZSH<CR>
:nnoremap <silent><leader>ep :e $MYPROFILE<CR>
:nnoremap <silent><leader>ed :e $MYTODOS<CR>
" Clear search {{{2
:nnoremap <silent><leader>/ :nohlsearch<CR>
" Easy command Mode {{{2
:nnoremap ; :
" Easy begin/end line navigation {{{2
:nnoremap H 0w
:nnoremap L $
" Easy clipboard copy {{{2
:vnoremap <silent><leader>c :w !pbcopy<CR><CR>
" Easy clipboard paste {{{2
:nnoremap <silent><leader>v :r !pbpaste<CR><CR>
" Easy grep under cursor {{{2
:nmap <silent><leader>r viw"ry:Ag! <C-R>r<CR><CR>
" Easy code folding {{{2
:nnoremap <Space> za
" Focus fold {{{2
:nnoremap <leader>f zMzA
" Toggle lint errors/warnings
:nnoremap <leader>A :ALEToggle<CR><CR>
" Quick newline {{{2
:nnoremap <CR> o<Esc>
" Toggle NERDTree {{{2
:nnoremap <leader>nt :NERDTree<CR>
"
" Toggle show formatting {{{2
:nnoremap <leader>l :set list!<CR>
" Window manipulation {{{2
:nnoremap <leader>\ :vsp<CR>
:nnoremap <leader>m :vertical resize 80<CR>
" Fugitive shortcuts {{{2
:nnoremap <leader>gb :Gblame<CR>
" Tab switching {{{2
:nnoremap <leader>1 1gt
:nnoremap <leader>2 2gt
:nnoremap <leader>3 3gt
:nnoremap <leader>4 4gt
:nnoremap <leader>5 5gt
:nnoremap <leader>6 6gt
:nnoremap <leader>7 7gt
:nnoremap <leader>8 8gt
:nnoremap <leader>9 9gt
:nnoremap <leader>0 :tablast<CR>
:nnoremap <leader>x :tabclose<CR>
:nnoremap <leader>t :0tabnew<CR>
" Easy fzf {{{2
nmap ; :Buffers<CR>
nmap <leader>p :Files<CR>
" Toggle paste mode {{{2
:nnoremap <leader>P :set invpaste!<CR>
" Ctags navigation {{{2
:nnoremap <leader>g <C-]>
:nnoremap <leader>b <C-t>
" Easy Ack/Ag {{{2
:nnoremap <leader>a :Ag
" Easy commenting {{{2
:nnoremap // :TComment<CR>
:vnoremap // :TComment<CR>
" Prevent overwriting default register (system clipboard) when inconvenient {{{2
:vnoremap x "_x
:vnoremap c "_c
:vnoremap p "_dP
" Don't use arrow keys in normal mode :) {{{2
:nnoremap <Left> <NOP>
:nnoremap <Right> <NOP>
:nnoremap <Up> <NOP>
:nnoremap <Down> <NOP>
" In insert or command mode, move normally by using Ctrl {{{2
inoremap <C-h> <Left>
inoremap <C-j> <Down>
inoremap <C-k> <Up>
inoremap <C-l> <Right>
cnoremap <C-h> <Left>
cnoremap <C-j> <Down>
cnoremap <C-k> <Up>
cnoremap <C-l> <Right>
" Enables filetype detection and loads indent files {{{2
" Note: It's important this called after vim/bundle is added to vim's
" runtime path so that ftdetect will be loaded
" Thanks: http://stackoverflow.com/a/19314347
filetype plugin indent on
" Set path for fzf
set rtp+=/usr/local/opt/fzf
" Use Omni-Completion
set omnifunc=syntaxcomplete#Complete
" Plugins {{{1
" Ag {{{2
if executable('ag')
" Use ag over grep
set grepprg=ag\ --nogroup\ --nocolor
" use ag over ack
let g:ackprg = 'ag --vimgrep'
endif
" Lightline {{{2
" General settings
let g:lightline = {
\ 'colorscheme': 'jellybeans',
\ 'mode_map': { 'c': 'NORMAL' },
\ 'active': {
\ 'left': [ [ 'mode', 'paste' ], [ 'fugitive', 'filename' ] ]
\ },
\ 'component_function': {
\ 'fugitive': 'MyFugitive'
\ },
\ 'separator': { 'left': "", 'right': '' },
\ 'subseparator': { 'left': '|', 'right': '|' }
\ }
" NERDTree {{{2
" Files and directories I don't want to see
" Note the use of vim-style regex
let NERDTreeIgnore = [
\ '\.\(pyc\|swp\|db\|coverage\|DS_Store\)$',
\ '\.\(git\|hg\|svn\|egg-info\)$[[dir]]',
\ '\(coverage\|pytests\)\.xml$',
\ ]
" I do want to see dotfiles (like .gitignore)
let NERDTreeShowHidden=1
" Pretty NERDTree
let NERDTreeMinimalUI = 1
let NERDTreeDirArrows = 1
" vim-javascript {{{2
" Enable syntax highlighting for flow
let g:javascript_plugin_flow = 1
" ale {{{2
" Configure error and warning formatting
let g:ale_sign_error = '✘'
let g:ale_sign_warning = '⚠'
highlight ALEErrorSign ctermbg=NONE ctermfg=red
highlight ALEWarningSign ctermbg=NONE ctermfg=yellow
let g:ale_lint_on_enter = 0 " Don't lint files on open
let g:ale_sign_column_always = 1 " Keep column open by default
" Linters
let g:ale_linters = {
\ 'javascript': ['eslint'],
\}
let g:ale_linters_explicit = 1
" Fixers
let g:ale_fixers = {
\ 'javascript': ['eslint']
\ }
" vim-jsx-pretty {{{2
" Colorful style
let g:vim_jsx_pretty_colorful_config = 1
" vim-prettier {{{2
" Run prettier async
let g:prettier#exec_cmd_async = 1
" Custom functions {{{1
" Strip whitespace and save cursor position {{{2
function! <SID>StripTrailingWhitespaces()
" Preparation: save last search, and cursor position.
let _s=#/
let l = line(".")
let c = col(".")
" Do the business:
%s/\s\+$//e
" Clean up: restore previous search history, and cursor position
let #/=_s
call cursor(l, c)
endfunction
" Displays current git branch in powerline {{{2
function! MyFugitive()
if &ft !~? 'vimfiler\|gundo' && exists("*fugitive#head")
let _ = fugitive#head()
return strlen(_) ? "\u00A7 "._ : ''
endif
return ''
endfunction
" }}}
" Autocommands {{{1
augroup configgroup
" Clear previous autocmds
autocmd!
" White Space Settings for different file types {{{2
autocmd FileType python setlocal ts=4 sts=4 sw=4 et
autocmd FileType javascript,jsx,tsx setlocal ts=2 sts=2 sw=2 et
autocmd FileType css setlocal ts=2 sts=2 sw=2 et
autocmd FileType ruby setlocal ts=2 sts=2 sw=2 et
autocmd FileType html,htmljinja setlocal ts=2 sts=2 sw=2 et
" Clean up trailing white spaces {{{2
autocmd BufWritePre * :call <SID>StripTrailingWhitespaces()
" Python folding {{{2
au FileType python setlocal foldmethod=indent
au FileType python setlocal foldlevel=0
" Javascript folding {{{2
au FileType javascript,jsx,tsx setlocal foldmethod=syntax
au FileType javascript,jsx,tsx setlocal foldlevel=1
" Rainbow-ify parens/brackets for selected file types {{{2
au FileType javascriptreact,jsx call rainbow#load()
" Enable vim-jinja highlighting for .jinja files {{{2
autocmd BufNewFile,BufRead *.jinja set filetype=htmljinja
" Trigger autoread whenever I switch buffer or when focusing vim again {{{2
" Thanks: http://stackoverflow.com/questions/2490227/how-does-vims-autoread-work/20418591#20418591
au FocusGained,BufEnter * :silent! !
" Save whenever switching between windows and buffers {{{2
au FocusLost,BufLeave,WinLeave * :silent! w
" Close the Omni-Completion tip window when a selection is made {{{2
" These lines close it on movement in insert mode or when leaving insert mode
" Thanks:
" http://stackoverflow.com/questions/3105307/how-do-you-automatically-remove-the-preview-window-after-autocompletion-in-vim
autocmd CursorMovedI * if pumvisible() == 0|pclose|endif
autocmd InsertLeave * if pumvisible() == 0|pclose|endif
" }}} End section
augroup END
" COC {{{1
" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable
" delays and poor user experience.
set updatetime=300
" Use tab for trigger completion with characters ahead and navigate.
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config.
inoremap <silent><expr> <TAB>
\ pumvisible() ? "\<C-n>" :
\ <SID>check_back_space() ? "\<TAB>" :
\ coc#refresh()
inoremap <expr><S-TAB> pumvisible() ? "\<C-p>" : "\<C-h>"
function! s:check_back_space() abort
let col = col('.') - 1
return !col || getline('.')[col - 1] =~# '\s'
endfunction
" Use <c-space> to trigger completion.
if has('nvim')
inoremap <silent><expr> <c-space> coc#refresh()
else
inoremap <silent><expr> <c-#> coc#refresh()
endif
" Make <CR> auto-select the first completion item and notify coc.nvim to
" format on enter, <cr> could be remapped by other vim plugin
inoremap <silent><expr> <cr> pumvisible() ? coc#_select_confirm()
\: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
" Remap keys for gotos
nmap <silent> gd <Plug>(coc-definition)
nmap <leader>u <Plug>(coc-references)
nmap <leader>rn <Plug>(coc-rename)
command! -nargs=0 Format :call CocAction('format')
" Diagnostics
inoremap <silent><expr> <c-space> coc#refresh()
nmap <silent> [l <Plug>(coc-diagnostic-prev)
nmap <silent> ]l <Plug>(coc-diagnostic-next)
nmap <silent> [k :CocPrev<cr>
nmap <silent> ]k :CocNext<cr>
" Highlight symbol under cursor on CursorHold
autocmd CursorHold * silent call CocActionAsync('highlight')
vmap <leader>f <Plug>(coc-format-selected)
nmap <leader>f <Plug>(coc-format-selected)
" Fix autofix problem of current line
nmap <leader>aq <Plug>(coc-fix-current)
" Show documentation
nnoremap <silent> K :call <SID>show_documentation()<CR>
function! s:show_documentation()
if &filetype == 'vim'
execute 'h '.expand('<cword>')
else
call CocAction('doHover')
endif
endfunction
autocmd BufReadCmd,FileReadCmd,SourceCmd jar:file://* call s:LoadClojureContent(expand("<amatch>"))
function! s:LoadClojureContent(uri)
setfiletype clojure
let content = CocRequest('clojure-lsp', 'clojure/dependencyContents', {'uri': a:uri})
call setline(1, split(content, "\n"))
setl nomodified
setl readonly
endfunction
" }}} End Section
" Source private vimrc {{{1
if filereadable(expand("~/.vim/vimrc.private.after"))
source ~/.vim/vimrc.private.after
endif
Help would be much appreciated. Mainky:
Why is the diagnostic window full-screen?
Is there a way I could configure this to be smaller, or to show up somewhere else? (perhaps below the main pane)
Problem was
" Auto adjust window sizes when they become current {{{2
set winwidth=84
set winheight=5
set winminheight=5
set winheight=999
" }}} End section
Removing this did the trick

How to hide all source code tooltips in MacVim?

I installed MacVim 7.4-73_1 on MacOs X Yosemite using Homebrew. When in a ruby file hovering over certain words will cause a tooltip to fade in. It seems to slow Vim down causing a short lag while the tooltip loads, they also tend to get in the way. So, my goal is to hide these tooltips all together. I understand this may be caused by a plugin I am using but I can't seem to pin it down.
I have attached a gif below showing another strange behavior. The tooltips only show up if I begin editing a file from the vim explorer.
Below is a list of the vim plugins I am using and my .vimrc
All my plugins
ack.vim
mustache
nerdcommenter
sass-convert.vim
snipmate-mocha
snipmate-snippets
tabular
tlib_vim
vim-addon-mw-utils
vim-coffee-script
vim-css-color
vim-fugitive
vim-less
vim-rails
vim-rspec
vim-snipmate
My Vimrc File
" Use Pathogen
call pathogen#runtime_append_all_bundles()
call pathogen#helptags()
" ================
" Ruby stuff
" ================
syntax on " Enable syntax highlighting
filetype plugin indent on " Enable filetype-specific indenting and plugins
augroup myfiletypes
" Clear old autocmds in group
autocmd!
" autoindent with two spaces, always expand tabs
autocmd FileType ruby,eruby,yaml set ai sw=2 sts=2 et
augroup END
"================
let mapleader = ","
" START html.tidy
:vmap <Leader>ti :!tidy -q -i --show-errors 0<CR>
" START TAB.vim
nmap <Leader>a{ :Tabularize /{<CR>
vmap <Leader>a= :Tabularize /=<CR>
nmap <Leader>a= :Tabularize /=<CR>
nmap <Leader>a. :Tabularize /=><CR>
vmap <Leader>a. :Tabularize /=><CR>
nmap <Leader>a: :Tabularize /:\zs<CR>
vmap <Leader>a: :Tabularize /:\zs<CR>
"inoremap <silent> = =<Esc>:call <SID>ealign()<CR>a
function! s:ealign()
let p = '^.*=[^>]*$'
if exists(':Tabularize') && getline('.') =~# '^.*=' && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
let column = strlen(substitute(getline('.')[0:col('.')],'[^=]','','g'))
let position = strlen(matchstr(getline('.')[0:col('.')],'.*=\s*\zs.*'))
Tabularize/=/l1
normal! 0
call search(repeat('[^=]*=',column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
endif
endfunction
"inoremap <silent> => =><Esc>:call <SID>ralign()<CR>a
function! s:ralign()
let p = '^.*=>*$'
if exists(':Tabularize') && getline('.') =~# '^.*=>' && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
let column = strlen(substitute(getline('.')[0:col('.')],'[^=>]','','g'))
let position = strlen(matchstr(getline('.')[0:col('.')],'.*=>\s*\zs.*'))
Tabularize/=/l1
normal! 0
call search(repeat('[^=>]*=>',column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
endif
endfunction
inoremap <silent> <Bar> <Bar><Esc>:call <SID>palign()<CR>a
function! s:palign()
let p = '^\s*|\s.*\s|\s*$'
if exists(':Tabularize') && getline('.') =~# '^\s*|' && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
let column = strlen(substitute(getline('.')[0:col('.')],'[^|]','','g'))
let position = strlen(matchstr(getline('.')[0:col('.')],'.*|\s*\zs.*'))
Tabularize/|/l1
normal! 0
call search(repeat('[^|]*|',column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
endif
endfunction
" END TAB.vim
noremap <Up> <nop>
noremap <Down> <nop>
noremap <Left> <nop>
noremap <Right> <nop>
" START rspec.vim
"map <Leader>t :call RunCurrentSpecFile()<CR>
"map <Leader>s :call RunNearestSpec()<CR>
"map <Leader>l :call RunLastSpec()<CR>
map <Leader>ra :call RunAllSpecs()<CR>
" END rspec.vim
set nocompatible
set backspace=indent,eol,start " allow backspacing over everything in insert mode
set history=500 " keep 500 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set autoindent " indent next line
set showmatch " Attempts to show matching (), {}, or []
set nowrap
"set nobackup
"set noswapfile
set backupdir=~/.tmp
set directory=~/.tmp " Don't clutter my dirs up with swp and tmp files
set autoread
set wmh=0 " This sets the minimum window height to 0, so you can stack many more files before things get crowded. Vim will only display the filename.
set viminfo+=!
" Edit another file in the same directory as the current file
" uses expression to extract path from current file's path
map <Leader>e :Explore
map <Leader>ep :e <C-R>=expand("%:p:h") . '/'<CR>
map <Leader>s :Sexplore
map <Leader>v :Vexplore
map <Leader>nt :tabe <C-R>=expand("%:p:h") . '/'<CR>
" Easy window navigation
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
vmap <leader>h :!/Users/ross/.rvm/bin/vim_html2haml<cr>
function! PasteAsCoffee()
:read !pbpaste | js2coffee
endfunction
:command! PasteAsCoffee :call PasteAsCoffee()
:map <leader>pc :PasteAsCoffee<CR>
set tabstop=2 " Set tabs to 2 spaces
set autowriteall " Auto save on close
set spell
set list
set listchars=tab:>.,trail:.,extends:#,nbsp:. " Highlight problematic whitespace
set et " expand tab
set sw=2 " shift width < >
set smarttab " deltes of adds a tab
set tw=80 " auto break lines at 80 columns
set incsearch " don't show search matches as you type
set ignorecase smartcase " when searching ignore case when the pattern contains lowercase letters only.
set laststatus=2 " show status line. never=0 only when split=1 always=2
set number " show line numbers
set gdefault " assume the /g flag on :s substitutions to replace all matches in a line
set autoindent " always set autoindenting on
set pastetoggle=<F2> " Don't auto indent pasted text after F2
let g:netrw_preview = 1
let g:fuzzy_ignore = ".DS_Store;*.png;*.PNG;*.JPG;*.jpg;*.GIF;*.gif;vendor/**;coverage/**;tmp/**;rdoc/**"
set nofoldenable " Say no to code folding...
set statusline+=%<%f\ %h%m%r%{fugitive#statusline()}%=%-14.(%l,%c%V%)\ %P
" I don't remember what this does
autocmd BufEnter * silent! lcd %:p:h
" remove search highlight with ,/
nmap <silent> ,/ :nohlsearch<CR>
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
endif " has("autocmd")
colors codeschool
You can read about that feature in :help balloon-eval.
That option is disabled by default so one of your plugins probably enabled it. This command should show you which one is the culprit:
:verbose set ballooneval?
You can disable that feature with :set noballooneval.

Is there anyway to change VIM Surround's keymapping?

I currently have my .vimrc set up so that
s saves my file
d deletes any text that is highlighted in visual mode
c will comment any line the cursor is on (or any group of highlighted lines)
so obviously this prevents me from using Surround's default commands. Is there a way I can make my own commands in .vimrc to replace Surround's default ones?
Here is my .vimrc
set nocompatible
filetype off " required!
set rtp+=~/.vim/bundle/vundle
call vundle#rc()
" let Vundle manage Vundle
" required!
Bundle 'gmarik/vundle'
" My Bundles here:
"
" original repos on github
Bundle 'tpope/vim-fugitive'
Bundle 'jistr/vim-nerdtree-tabs'
" Bundle 'tpope/vim-haml'
Bundle 'ap/vim-css-color'
Bundle 'Lokaltog/vim-easymotion'
Bundle 'rstacruz/sparkup', {'rtp': 'vim/'}
Bundle "pangloss/vim-javascript"
" vim-scripts repos
Bundle 'surround.vim'
Bundle 'delimitMate.vim'
Bundle 'hail2u/vim-css3-syntax'
" Bundle 'AutoComplPop'
" Bundle 'ervandew/supertab'
Bundle 'snipMate'
Bundle 'tComment'
" Bundle 'mru.vim'
Bundle 'scrooloose/nerdtree'
Bundle 'matchit.zip'
Bundle 'Vimball'
Bundle 'ScrollColors'
Bundle 'L9'
Bundle 'FuzzyFinder'
" non github repos
Bundle 'git://git.wincent.com/command-t.git'
" Shortcuts
" Basic pair completion
" inoremap { {}<Left>
" inoremap {<CR> {<CR>}<Esc>O
" inoremap {{ {
" inoremap {} {}
" inoremap : :;<Left>
"inoremap :<CR> :;
"noremap :: :;<Left>
"inoremap :; :;
" Create new buffers vertically or horizontally
nnoremap ,v <C-w>v
nnoremap ,h <C-w>s
" Toggle between the buffers
nnoremap ,, <C-w>w
" Increase or decrease buffer size
noremap <C-Up> <C-W>+
noremap <C-Down> <C-W>-
noremap <C-Left> <C-W>>
noremap <C-Right> <C-W><
nmap gf <S-g>
nmap f :FufFile <CR>
vmap c gc
nmap c gcc
nmap tt :tabnew <CR>
nmap tc :tabclose <CR>
nmap ml :MRU <CR>
nmap ,n :NERDTree <CR>;
nmap s :w! <CR>
nmap q :q! <CR>
syntax on
set mouse=a "enables mouse
" map <F2> :NERDTreeToggle<CR>;
map <F2> :NERDTreeTabsToggle<CR>;
" Selecting different color schemes
map <silent> ,3 :NEXTCOLOR<cr>
map <silent> ,2 :PREVCOLOR<cr>
map <silent> ,1 :SCROLL<cr>
" Directory Set up
set backup "backs up files
set backupdir=$HOME/.vimbackup
set directory=$HOME/.vimswap
set viewdir=$HOME/.vimviews
"
" silent execute '!mkdir -p $HOME/.vimbackup'
" silent execute '!mkdir -p $HOME/.vimswap'
" silent execute '!mkdir -p $HOME/.vimviews'
" au BufWinLeave * silent! mkview "makes vim save view state
" au BufWinEnter * silent! loadview "makes vim load view state
" Appearance
set columns=60
set guifont=Monaco\ 11
if has("autocmd")
au InsertEnter * silent execute "!gconftool-2 --type string --set /apps/gnome-terminal/profiles/Default/cursor_shape ibeam"
au InsertLeave * silent execute "!gconftool-2 --type string --set /apps/gnome-terminal/profiles/Default/cursor_shape block"
au VimLeave * silent execute "!gconftool-2 --type string --set /apps/gnome-terminal/profiles/Default/cursor_shape ibeam"
endif
" set guicursor=n-v-c:block-Cursor
" set guicursor+=i:ver100-iCursor
" set guicursor+=n-v-c:blinkon0
" set guicursor+=i:blinkwait10
if has("gui_running")
set guioptions=aiA " Disable toolbar, menu bar, scroll bars
colorscheme jellybeans
else
colorscheme desert256
endif " has("gui_running")
set t_Co=256
set tabpagemax=10 "show only 10 tabs
set background=dark
set number
set scrolloff=3 "minimum lines to keep above/below cursor
set foldenable "auto fold code
set foldmethod=manual
" Behaviour
" set nowrap "wrap long lines
set linebreak
:filetype plugin indent on " lets filetype plugins be used
" Treat SCSS files as CSS files
" au BufRead,BufNewFile *.scss set filetype=css
" Close VIM even if NERDTree is the last buffer
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif
" after appending closing delimiter, it indents
let delimitMate_expand_cr=1
" if bufwinnr(1)
" map <kPlus><C-W>+
" map <kMinus><C-W>-
" map <kDivide><c-w><
" map <kMultiply><c-w>>
" endif
set autoindent
set smartindent
set tabstop=2
set shiftwidth=2
set smarttab
set expandtab
set softtabstop=2
set spell
set showmatch "shows matching parens, brackets
set winminheight=0
set go-=T "eliminates tool bar in gVim
set go-=m "eliminates menu bar in gVim
set go-=r "eliminates right scroll bar
set lines=50 "50 lines of text instead of 24
set backspace=2 "makes backspace work like normally it does
:fixdel
set vb t_vb= "prevents vim from beeping when command is bad. instead it flashes screen.
set ruler "shows statusline, displays curor position
set incsearch "vim searches text as you enter it
" set hlsearch "hilights searched items
set ignorecase "case insensitive search
set smartcase "case sensetive when using captials
set wildmenu "shows list instead of completing
set wildmode=list:longest,full "command <TAB> completeiton, lists matches,
set virtualedit=all "lets cursor freely roam anywhere like in command mode
If you take a look at the source for the surround plugin you'll notice the following block:
if !exists("g:surround_no_mappings") || ! g:surround_no_mappings
nmap ds <Plug>Dsurround
nmap cs <Plug>Csurround
nmap ys <Plug>Ysurround
nmap yS <Plug>YSurround
nmap yss <Plug>Yssurround
nmap ySs <Plug>YSsurround
nmap ySS <Plug>YSsurround
xmap S <Plug>VSurround
xmap gS <Plug>VgSurround
if !exists("g:surround_no_insert_mappings") || ! g:surround_no_insert_mappings
if !hasmapto("<Plug>Isurround","i") && "" == mapcheck("<C-S>","i")
imap <C-S> <Plug>Isurround
endif
imap <C-G>s <Plug>Isurround
imap <C-G>S <Plug>ISurround
endif
endif
As you can see, you can prevent the plugin from mapping anything by adding the following to your .vimrc:
let g:surround_no_mappings = 1
Then you can add your own mappings for the functions defined in these blocks.

Reloading .vimrc in autocmd breaks Powerline

I know this has already been discussed, but the proposed solution is not working for me.
I have this in my .vimrc:
autocmd! BufWritePost .vimrc nested source $MYVIMRC
Since I read that the correct way to source .vimrc inside an autocmd is using autocmd-nested.
Still, everytime I save it I lose colors in powerline
Edit:
here is my .vimrc
filetype off
set rtp+=~/.vim/vundle.git/
call vundle#rc()
set rtp+=~/.vim/bundle/powerline/powerline/bindings/vim
"set statusline+=%#warningmsg#
"set statusline+=%{SyntasticStatuslineFlag()}
"set statusline+=%*
let g:syntastic_enable_signs=1
let g:syntastic_auto_loc_list=1
let g:ctrlp_working_path_mode = 'ra'
" Bundles
"
" original repos on github
"Bundle 'vim-scripts/taglist.vim'
Bundle 'majutsushi/tagbar'
"Bundle 'joonty/vim-phpqa.git'
"Bundle 'joonty/vim-phpunitqf'
Bundle 'joonty/vdebug'
" Php
Bundle 'sumpygump/php-documentor-vim'
Bundle 'sophacles/vim-processing'
Bundle 'nelstrom/vim-visual-star-search'
Bundle 'Lokaltog/powerline'
Bundle 'spolu/dwm.vim'
Bundle 'tpope/vim-unimpaired'
Bundle 'airblade/vim-gitgutter'
Bundle 'kien/ctrlp.vim'
Bundle 'wikitopian/hardmode'
Bundle 'tpope/vim-fugitive'
Bundle 'sbl/scvim'
Bundle 'vim-scripts/bufexplorer'
Bundle 'aaronbieber/quicktask'
Bundle 'vim-scripts/The-NERD-Commenter'
Bundle 'tpope/vim-fugitive'
Bundle 'tpope/vim-surround'
Bundle 'vim-scripts/HTML-AutoCloseTag'
Bundle 'scrooloose/nerdtree'
"Bundle 'scrooloose/syntastic'
Bundle 'vim-scripts/css_color.vim'
" Color schemes
Bundle 'tomasr/molokai'
Bundle 'altercation/vim-colors-solarized'
Bundle 'vim-scripts/OOP-javascript-indentation'
let g:gitgutter_enabled = 0
set nocompatible "Don't be compatible with vi
" Enable filetype plugin
filetype indent on
filetype plugin on
" Set to auto read when a file is changed from the outside
set autoread
set t_Co=16
set background=dark
set number "Show line numbering
set numberwidth=1 "Use 1 col + 1 space for numbers
" With a map leader it's possible to do extra key combinations
let mapleader = ","
let g:mapleader = ","
" Toggle NERDTree
map <leader>n :NERDTreeToggle<CR>
set backupdir=~/.vim/backup " where to put backup files
set directory=~/.vim/temp " where to put swap files
" Fast saving
nmap <leader>w :w!<cr>
" Fast editing of the .vimrc
map <leader>e :e $MYVIMRC<cr>
" When .vimrc is edited, reload it
augroup MyAutoCmd
autocmd!
augroup END
autocmd MyAutoCmd BufWritePost $MYVIMRC nested source $MYVIMRC
"au! BufWritePost .vimrc nested source %
set title
" Remap esc key
inoremap jk <esc>
" work more logically with wrapped lines
noremap j gj
noremap k gk
set smartcase " search case sensitive if caps on
set showcmd " Display what command is waiting for an operator
autocmd BufNewFile,BufRead /*apache* setfiletype apache
autocmd BufNewFile,BufRead /*lighttpd*.conf setfiletype lighty
autocmd BufNewFile,BufRead {.,_}vimrc set foldmethod=marker
" PhpDocumentor
au BufRead,BufNewFile *.php inoremap <buffer> <leader>p :call PhpDoc()<CR>
au BufRead,BufNewFile *.php nnoremap <buffer> <leader>p :call PhpDoc()<CR>
au BufRead,BufNewFile *.php vnoremap <buffer> <leader>p :call PhpDocRange()<CR>
" Nicer highlighting of completion popup
highlight Pmenu guibg=brown gui=bold
set scrolloff=7 "Set 7 lines to the cursors when moving vertical
set wildmenu "Autocomplete features in the status bar
set ruler "Always show current position
set cmdheight=2 "The commandbar height
set hidden "Change buffer without saving
" Backspae config
set backspace=eol,start,indent
set whichwrap+=<,>,h,l
set ignorecase "Search is case insensitive
set hlsearch "Highlight matches to the search
set incsearch "Show best match so far
set magic "Set magic on for regular expressions
set showmatch "Show matching bracets when text indicator is over them
set mat=2 "How many tenths of a second to blink
" No sound on errors
set noerrorbells
set novisualbell
set t_vb=
" Colors and fonts {{{1
set term=screen-256color
syntax enable "Enable syntax hl
syntax on "Enable syntax hl
"colorscheme molokai
"let g:solarized_termcolors=256
colorscheme solarized
set guifont=Envy\ Code\ R\ for\ Powerline
set encoding=utf-8
filetype plugin on
"set guifont=Inconsolata\ for\ Powerline\
let g:Powerline_symbols="fancy"
" Text, tab and indent related {{{1
set expandtab "Transform tabs into spaces
set shiftwidth=4 "sw 4 spaces (used on auto indent)
set shiftwidth=4 "sw 4 spaces (used on auto indent)
set tabstop=4 "4 spaces as a tab for bs/del
set smarttab
set wrap linebreak tw=80 wm=0 "Wrap lines
set ai "Auto indent
set si "Smart indent
" }}}1
" Moving around, tabs and buffers {{{1
" Move to previous and next buffer
:nmap <C-n> :bnext<CR>
:nmap <C-p> :bprev<CR>
" Map space to / (search) and c-space to ? (backwards search)
map <space> /
map <c-space> ?
map <silent> <leader><cr> :noh<cr>
" Smart way to move between windows
map <C-j> <C-W>j
map <C-k> <C-W>k
map <C-h> <C-W>h
map <C-l> <C-W>l
" Mappings to access buffers (don't use "\p" because a
" delay before pressing "p" would accidentally paste).
" ,l : list buffers
" ,b ,f ,g : go back/forward/last-used
" ,1 ,2 ,3 : go to buffer 1/2/3 etc
nnoremap <Leader>l :ls<CR>
nnoremap <Leader>b :bp<CR>
nnoremap <Leader>f :bn<CR>
nnoremap <Leader>g :e#<CR>
nnoremap <Leader>1 :1b<CR>
nnoremap <Leader>2 :2b<CR>
nnoremap <Leader>3 :3b<CR>
nnoremap <Leader>4 :4b<CR>
nnoremap <Leader>5 :5b<CR>
nnoremap <Leader>6 :6b<CR>
nnoremap <Leader>7 :7b<CR>
nnoremap <Leader>8 :8b<CR>
nnoremap <Leader>9 :9b<CR>
nnoremap <Leader>0 :10b<CR>
" Close the current buffer. Bclose defined below.
" dovrebbe già esistere in bufkill.vim
" map <leader>bd :Bclose<cr>
" Use the arrows to do something useful
map <right> :bn<cr>
map <left> :bp<cr>
" MiniBufExplorer settings
let g:miniBufExplModSelTarget = 1
let g:miniBufExplorerMoreThanOne = 2
let g:miniBufExplModSelTarget = 0
let g:miniBufExplUseSingleClick = 1
let g:miniBufExplMapWindowNavVim = 1
" Change directory to the file I'm editing
"autocmd BufEnter * lcd %:p:h
" When pressing <leader>cd switch to the directory of the open buffer
map <leader>cd :cd %:p:h<cr>
" Function to close buffer?
command! Bclose call <SID>BufcloseCloseIt()
function! <SID>BufcloseCloseIt()
let l:currentBufNum = bufnr("%")
let l:alternateBufNum = bufnr("#")
if buflisted(l:alternateBufNum)
buffer #
else
bnext
endif
if bufnr("%") == l:currentBufNum
new
endif
if buflisted(l:currentBufNum)
execute("bdelete! ".l:currentBufNum)
endif
endfunction
" Specify the behavior when switching between buffers
try
set switchbuf=usetab
set stal=2
catch
endtry
nnoremap <C-e> 3<C-e>
nnoremap <C-y> 3<C-y>
" Always hide the statusline
set laststatus=2
" Format the statusline
set statusline=\ %F%m%r%h\ %w\ \ [%Y]\ \ CWD:\ %r%{CurDir()}%h\ \ \ Line:\ %l/%L:%c
"set statusline=%F%m%w\ Line:\ %l\/%L[%p%%]\ Col:\ %c\ Buf:\ #%n\ [%Y]\ [\%03.3b]\[\%02.2B]
function! CurDir()
let curdir = substitute(getcwd(), '/Users/amir/', "~/", "g")
return curdir
endfunction
" tab labels show the filename without path(tail)
set guitablabel=%N/\ %t\ %M
""" Windows
if exists(":tab") " Try to move to other windows if changing buf
set switchbuf=useopen,usetab
else " Try other windows & tabs if available
set switchbuf=useopen
endif
"""" Messages, Info, Status
set shortmess+=a " Use [+] [RO] [w] for modified, read-only, modified
set report=0 " Notify me whenever any lines have changed
set confirm " Y-N-C prompt if closing with unsaved changes
" we don't want to edit these type of files
set wildignore=*.o,*.obj,*.bak,*.exe,*.pyc,*.swp
"""" Coding
set history=1000 " 1000 Lines of history
set showfulltag " Show more information while completing tags
" taglist plugin settings
"nnoremap <silent> <F8> :TlistToggle<CR>
let Tlist_Exit_OnlyWindow = 1 "exit if taglist is last window open
let Tlist_Show_One_File = 1 "only show tags for current buffer
let Tlist_Enable_Fold_Column = 0 "no fold column (only showing one file)
" OmniCppComplete
let OmniCpp_NamespaceSearch = 1
let OmniCpp_GlobalScopeSearch = 1
let OmniCpp_ShowAccess = 1
let OmniCpp_ShowPrototypeInAbbr = 1 " show function parameters
let OmniCpp_MayCompleteDot = 1 " autocomplete after .
let OmniCpp_MayCompleteArrow = 1 " autocomplete after ->
let OmniCpp_MayCompleteScope = 1 " autocomplete after ::
let OmniCpp_DefaultNamespaces = ["std", "_GLIBCXX_STD"]
" automatically open and close the popup menu / preview window
au CursorMovedI,InsertLeave * if pumvisible() == 0|silent! pclose|endif
set completeopt=menuone,menu,longest,preview
let g:sparkupNextMapping = '<c-x>'
" SuperTab settings
let g:SuperTabDefaultCompletionType = '<c-x><c-o>'
""""" Folding
set foldmethod=syntax " By default, use syntax to determine folds
set foldlevelstart=99 " All folds open by default
" Function to highlight character beyond column 79
" activate it with ,h
nnoremap <leader>h :call ToggleOverLengthHighlight()<CR>
let g:overlength_enabled = 0
" set the highlight color
highlight OverLength ctermbg=red guibg=red
function! ToggleOverLengthHighlight()
if g:overlength_enabled == 0
match OverLength /\%79v.*/
let g:overlength_enabled = 1
echo 'OverLength highlighting turned on'
else
match
let g:overlength_enabled = 0
echo 'OverLength highlighting turned off'
endif
endfunction
" in visual mode press Ctrl r to start substituting text
vnoremap <C-r> "hy:%s/<C-r>h//gc<left><left><left>
" PHP Code Sniffer binary (default = "phpcs")
let g:phpqa_codesniffer_cmd='vendor/bin/phpcs'
" PHP Mess Detector binary (default = "phpmd")
let g:phpqa_messdetector_cmd='vendor/bin/phpmd'
set relativenumber
" important
" moving around, searching and patterns
" tags
" displaying text
" syntax, highlighting and spelling
" multiple windows
" multiple tab pages
" terminal
" using the mouse
" printing
" messages and info
" selecting text
" editing text
" tabs and indenting
" folding
" diff mode
" mapping
" toggle the tag list
nmap <Leader>tl :TlistToggle<CR>
" reading and writing files
" the swap file
" command line editing
" executing external commands
" running make and jumping to errors
" language specific
" multi-byte characters
" various
" TagList options
" set the names of flags
let tlist_php_settings = 'php;c:class;f:function;d:constant;p:property'
" close all folds except for current file
let Tlist_File_Fold_Auto_Close = 1
" make tlist pane active when opened
let Tlist_GainFocus_On_ToggleOpen = 1
" width of window
let Tlist_WinWidth = 60
" close tlist when a selection is made
let Tlist_Close_On_Select = 1
" show the prototype
let Tlist_Display_Prototype = 1
" show tags only for current buffer
let Tlist_Show_One_File = 1
" Taglist variables
" Display function name in status bar:
let g:ctags_statusline=1
" Automatically start script
let generate_tags=1
" Displays taglist results in a vertical windows:
let Tlist_Use_Horiz_Window=0
" Shorter commands to toggle Taglist display
nnoremap TT :TlistToggle<CR>
map <F4> :TlistToggle<CR>
" Various Taglist display config:
let Tlist_Use_Right_Windows = 1
let Tlist_Compact_Format = 1
let Tlist_Exit_OnlyWindow = 1
let Tlist_GainFocus_On_ToggleOpen = 1
let Tlist_File_Fold_Auto_Close = 1
" Ctags options
nmap <Leader>tf :call CtagsFind(expand('<cword>'))<CR>
com! -nargs=+ Tf :call CtagsFind("<args>")
" split window and search for tag
nmap <Leader>ts :exe('stj '.expand('<cword>'))<CR>
set tags=tags;/
" open new tab and search for tag
"
fun! CtagsFind(keyword)
tabe
exe "tj ".a:keyword
endfunction
" TagBar
nmap <F8> :TagbarToggle<CR>
" CtrlP
let g:ctrlp_map = ',t'
nnoremap <silent> ,t :CtrlP<CR>
Your autocmd will be appended to your vim events.
You need handle reload with using augroup.
augroup MyAutoCmd
autocmd!
autocmd MyAutoCmd BufWritePost $MYVIMRC nested source $MYVIMRC
augroup END

What is in your .vimrc? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Vi and Vim allow for really awesome customization, typically stored inside a .vimrc file. Typical features for a programmer would be syntax highlighting, smart indenting and so on.
What other tricks for productive programming have you got, hidden in your .vimrc?
I am mostly interested in refactorings, auto classes and similar productivity macros, especially for C#.
You asked for it :-)
"{{{Auto Commands
" Automatically cd into the directory that the file is in
autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')
" Remove any trailing whitespace that is in the file
autocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif
" Restore cursor position to where it was before
augroup JumpCursorOnEdit
au!
autocmd BufReadPost *
\ if expand("<afile>:p:h") !=? $TEMP |
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ let JumpCursorOnEdit_foo = line("'\"") |
\ let b:doopenfold = 1 |
\ if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) |
\ let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 |
\ let b:doopenfold = 2 |
\ endif |
\ exe JumpCursorOnEdit_foo |
\ endif |
\ endif
" Need to postpone using "zv" until after reading the modelines.
autocmd BufWinEnter *
\ if exists("b:doopenfold") |
\ exe "normal zv" |
\ if(b:doopenfold > 1) |
\ exe "+".1 |
\ endif |
\ unlet b:doopenfold |
\ endif
augroup END
"}}}
"{{{Misc Settings
" Necesary for lots of cool vim things
set nocompatible
" This shows what you are typing as a command. I love this!
set showcmd
" Folding Stuffs
set foldmethod=marker
" Needed for Syntax Highlighting and stuff
filetype on
filetype plugin on
syntax enable
set grepprg=grep\ -nH\ $*
" Who doesn't like autoindent?
set autoindent
" Spaces are better than a tab character
set expandtab
set smarttab
" Who wants an 8 character tab? Not me!
set shiftwidth=3
set softtabstop=3
" Use english for spellchecking, but don't spellcheck by default
if version >= 700
set spl=en spell
set nospell
endif
" Real men use gcc
"compiler gcc
" Cool tab completion stuff
set wildmenu
set wildmode=list:longest,full
" Enable mouse support in console
set mouse=a
" Got backspace?
set backspace=2
" Line Numbers PWN!
set number
" Ignoring case is a fun trick
set ignorecase
" And so is Artificial Intellegence!
set smartcase
" This is totally awesome - remap jj to escape in insert mode. You'll never type jj anyway, so it's great!
inoremap jj <Esc>
nnoremap JJJJ <Nop>
" Incremental searching is sexy
set incsearch
" Highlight things that we find with the search
set hlsearch
" Since I use linux, I want this
let g:clipbrdDefaultReg = '+'
" When I close a tab, remove the buffer
set nohidden
" Set off the other paren
highlight MatchParen ctermbg=4
" }}}
"{{{Look and Feel
" Favorite Color Scheme
if has("gui_running")
colorscheme inkpot
" Remove Toolbar
set guioptions-=T
"Terminus is AWESOME
set guifont=Terminus\ 9
else
colorscheme metacosm
endif
"Status line gnarliness
set laststatus=2
set statusline=%F%m%r%h%w\ (%{&ff}){%Y}\ [%l,%v][%p%%]
" }}}
"{{{ Functions
"{{{ Open URL in browser
function! Browser ()
let line = getline (".")
let line = matchstr (line, "http[^ ]*")
exec "!konqueror ".line
endfunction
"}}}
"{{{Theme Rotating
let themeindex=0
function! RotateColorTheme()
let y = -1
while y == -1
let colorstring = "inkpot#ron#blue#elflord#evening#koehler#murphy#pablo#desert#torte#"
let x = match( colorstring, "#", g:themeindex )
let y = match( colorstring, "#", x + 1 )
let g:themeindex = x + 1
if y == -1
let g:themeindex = 0
else
let themestring = strpart(colorstring, x + 1, y - x - 1)
return ":colorscheme ".themestring
endif
endwhile
endfunction
" }}}
"{{{ Paste Toggle
let paste_mode = 0 " 0 = normal, 1 = paste
func! Paste_on_off()
if g:paste_mode == 0
set paste
let g:paste_mode = 1
else
set nopaste
let g:paste_mode = 0
endif
return
endfunc
"}}}
"{{{ Todo List Mode
function! TodoListMode()
e ~/.todo.otl
Calendar
wincmd l
set foldlevel=1
tabnew ~/.notes.txt
tabfirst
" or 'norm! zMzr'
endfunction
"}}}
"}}}
"{{{ Mappings
" Open Url on this line with the browser \w
map <Leader>w :call Browser ()<CR>
" Open the Project Plugin <F2>
nnoremap <silent> <F2> :Project<CR>
" Open the Project Plugin
nnoremap <silent> <Leader>pal :Project .vimproject<CR>
" TODO Mode
nnoremap <silent> <Leader>todo :execute TodoListMode()<CR>
" Open the TagList Plugin <F3>
nnoremap <silent> <F3> :Tlist<CR>
" Next Tab
nnoremap <silent> <C-Right> :tabnext<CR>
" Previous Tab
nnoremap <silent> <C-Left> :tabprevious<CR>
" New Tab
nnoremap <silent> <C-t> :tabnew<CR>
" Rotate Color Scheme <F8>
nnoremap <silent> <F8> :execute RotateColorTheme()<CR>
" DOS is for fools.
nnoremap <silent> <F9> :%s/$//g<CR>:%s// /g<CR>
" Paste Mode! Dang! <F10>
nnoremap <silent> <F10> :call Paste_on_off()<CR>
set pastetoggle=<F10>
" Edit vimrc \ev
nnoremap <silent> <Leader>ev :tabnew<CR>:e ~/.vimrc<CR>
" Edit gvimrc \gv
nnoremap <silent> <Leader>gv :tabnew<CR>:e ~/.gvimrc<CR>
" Up and down are more logical with g..
nnoremap <silent> k gk
nnoremap <silent> j gj
inoremap <silent> <Up> <Esc>gka
inoremap <silent> <Down> <Esc>gja
" Good call Benjie (r for i)
nnoremap <silent> <Home> i <Esc>r
nnoremap <silent> <End> a <Esc>r
" Create Blank Newlines and stay in Normal mode
nnoremap <silent> zj o<Esc>
nnoremap <silent> zk O<Esc>
" Space will toggle folds!
nnoremap <space> za
" Search mappings: These will make it so that going to the next one in a
" search will center on the line it's found in.
map N Nzz
map n nzz
" Testing
set completeopt=longest,menuone,preview
inoremap <expr> <cr> pumvisible() ? "\<c-y>" : "\<c-g>u\<cr>"
inoremap <expr> <c-n> pumvisible() ? "\<lt>c-n>" : "\<lt>c-n>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"
inoremap <expr> <m-;> pumvisible() ? "\<lt>c-n>" : "\<lt>c-x>\<lt>c-o>\<lt>c-n>\<lt>c-p>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"
" Swap ; and : Convenient.
nnoremap ; :
nnoremap : ;
" Fix email paragraphs
nnoremap <leader>par :%s/^>$//<CR>
"ly$O#{{{ "lpjjj_%A#}}}jjzajj
"}}}
"{{{Taglist configuration
let Tlist_Use_Right_Window = 1
let Tlist_Enable_Fold_Column = 0
let Tlist_Exit_OnlyWindow = 1
let Tlist_Use_SingleClick = 1
let Tlist_Inc_Winwidth = 0
"}}}
let g:rct_completion_use_fri = 1
"let g:Tex_DefaultTargetFormat = "pdf"
let g:Tex_ViewRule_pdf = "kpdf"
filetype plugin indent on
syntax on
This isn't in my .vimrc file, but yesterday I learned about the ]p command. This pastes the contents of a buffer just like p does, but it automatically adjusts the indent to match the line the cursor is on! This is excellent for moving code around.
I use the following to keep all the temporary and backup files in one place:
set backup
set backupdir=~/.vim/backup
set directory=~/.vim/tmp
Saves cluttering working directories all over the place.
You will have to create these directories first, vim will not create them for you.
Someone (viz. Frew) who posted above had this line:
"Automatically cd into the directory that the file is in:"
autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')
I was doing something like that myself until I discovered the same thing could be accomplished with a built in setting:
set autochdir
I think something similar has happened to me a few different times. Vim has so many different built-in settings and options that it's sometimes quicker and easier to roll-your-own than search the docs for the built-in way to do it.
My latest addition is for highlighting of the current line
set cul # highlight current line
hi CursorLine term=none cterm=none ctermbg=3 # adjust color
Update 2012: I'd now really recommend checking out vim-powerline which has replaced my old statusline script, albeit currently missing a few features I miss.
I'd say that the statusline stuff in my vimrc was probably most interesting/useful out of the lot (ripped from the authors vimrc here and corresponding blog post here).
Screenshot:
status line http://img34.imageshack.us/img34/849/statusline.png
Code:
"recalculate the trailing whitespace warning when idle, and after saving
autocmd cursorhold,bufwritepost * unlet! b:statusline_trailing_space_warning
"return '[\s]' if trailing white space is detected
"return '' otherwise
function! StatuslineTrailingSpaceWarning()
if !exists("b:statusline_trailing_space_warning")
if !&modifiable
let b:statusline_trailing_space_warning = ''
return b:statusline_trailing_space_warning
endif
if search('\s\+$', 'nw') != 0
let b:statusline_trailing_space_warning = '[\s]'
else
let b:statusline_trailing_space_warning = ''
endif
endif
return b:statusline_trailing_space_warning
endfunction
"return the syntax highlight group under the cursor ''
function! StatuslineCurrentHighlight()
let name = synIDattr(synID(line('.'),col('.'),1),'name')
if name == ''
return ''
else
return '[' . name . ']'
endif
endfunction
"recalculate the tab warning flag when idle and after writing
autocmd cursorhold,bufwritepost * unlet! b:statusline_tab_warning
"return '[&et]' if &et is set wrong
"return '[mixed-indenting]' if spaces and tabs are used to indent
"return an empty string if everything is fine
function! StatuslineTabWarning()
if !exists("b:statusline_tab_warning")
let b:statusline_tab_warning = ''
if !&modifiable
return b:statusline_tab_warning
endif
let tabs = search('^\t', 'nw') != 0
"find spaces that arent used as alignment in the first indent column
let spaces = search('^ \{' . &ts . ',}[^\t]', 'nw') != 0
if tabs && spaces
let b:statusline_tab_warning = '[mixed-indenting]'
elseif (spaces && !&et) || (tabs && &et)
let b:statusline_tab_warning = '[&et]'
endif
endif
return b:statusline_tab_warning
endfunction
"recalculate the long line warning when idle and after saving
autocmd cursorhold,bufwritepost * unlet! b:statusline_long_line_warning
"return a warning for "long lines" where "long" is either &textwidth or 80 (if
"no &textwidth is set)
"
"return '' if no long lines
"return '[#x,my,$z] if long lines are found, were x is the number of long
"lines, y is the median length of the long lines and z is the length of the
"longest line
function! StatuslineLongLineWarning()
if !exists("b:statusline_long_line_warning")
if !&modifiable
let b:statusline_long_line_warning = ''
return b:statusline_long_line_warning
endif
let long_line_lens = s:LongLines()
if len(long_line_lens) > 0
let b:statusline_long_line_warning = "[" .
\ '#' . len(long_line_lens) . "," .
\ 'm' . s:Median(long_line_lens) . "," .
\ '$' . max(long_line_lens) . "]"
else
let b:statusline_long_line_warning = ""
endif
endif
return b:statusline_long_line_warning
endfunction
"return a list containing the lengths of the long lines in this buffer
function! s:LongLines()
let threshold = (&tw ? &tw : 80)
let spaces = repeat(" ", &ts)
let long_line_lens = []
let i = 1
while i <= line("$")
let len = strlen(substitute(getline(i), '\t', spaces, 'g'))
if len > threshold
call add(long_line_lens, len)
endif
let i += 1
endwhile
return long_line_lens
endfunction
"find the median of the given array of numbers
function! s:Median(nums)
let nums = sort(a:nums)
let l = len(nums)
if l % 2 == 1
let i = (l-1) / 2
return nums[i]
else
return (nums[l/2] + nums[(l/2)-1]) / 2
endif
endfunction
"statusline setup
set statusline=%f "tail of the filename
"display a warning if fileformat isnt unix
set statusline+=%#warningmsg#
set statusline+=%{&ff!='unix'?'['.&ff.']':''}
set statusline+=%*
"display a warning if file encoding isnt utf-8
set statusline+=%#warningmsg#
set statusline+=%{(&fenc!='utf-8'&&&fenc!='')?'['.&fenc.']':''}
set statusline+=%*
set statusline+=%h "help file flag
set statusline+=%y "filetype
set statusline+=%r "read only flag
set statusline+=%m "modified flag
"display a warning if &et is wrong, or we have mixed-indenting
set statusline+=%#error#
set statusline+=%{StatuslineTabWarning()}
set statusline+=%*
set statusline+=%{StatuslineTrailingSpaceWarning()}
set statusline+=%{StatuslineLongLineWarning()}
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
"display a warning if &paste is set
set statusline+=%#error#
set statusline+=%{&paste?'[paste]':''}
set statusline+=%*
set statusline+=%= "left/right separator
function! SlSpace()
if exists("*GetSpaceMovement")
return "[" . GetSpaceMovement() . "]"
else
return ""
endif
endfunc
set statusline+=%{SlSpace()}
set statusline+=%{StatuslineCurrentHighlight()}\ \ "current highlight
set statusline+=%c, "cursor column
set statusline+=%l/%L "cursor line/total lines
set statusline+=\ %P "percent through file
set laststatus=2
Amongst other things, it informs on the status line of the usual standard file information but
also includes additional things like warnings for :set paste, mixed indenting, trailing
white space etc. Pretty useful if you're particularly anal about your
code formatting.
Furthermore and as shown in the screenshot, combining it with
syntastic allows any syntax errors to
be highlighted on it (assuming your language of choice has an associated syntax checker
bundled.
My mini version:
syntax on
set background=dark
set shiftwidth=2
set tabstop=2
if has("autocmd")
filetype plugin indent on
endif
set showcmd " Show (partial) command in status line.
set showmatch " Show matching brackets.
set ignorecase " Do case insensitive matching
set smartcase " Do smart case matching
set incsearch " Incremental search
set hidden " Hide buffers when they are abandoned
The big version, collected from various places:
syntax on
set background=dark
set ruler " show the line number on the bar
set more " use more prompt
set autoread " watch for file changes
set number " line numbers
set hidden
set noautowrite " don't automagically write on :next
set lazyredraw " don't redraw when don't have to
set showmode
set showcmd
set nocompatible " vim, not vi
set autoindent smartindent " auto/smart indent
set smarttab " tab and backspace are smart
set tabstop=2 " 6 spaces
set shiftwidth=2
set scrolloff=5 " keep at least 5 lines above/below
set sidescrolloff=5 " keep at least 5 lines left/right
set history=200
set backspace=indent,eol,start
set linebreak
set cmdheight=2 " command line two lines high
set undolevels=1000 " 1000 undos
set updatecount=100 " switch every 100 chars
set complete=.,w,b,u,U,t,i,d " do lots of scanning on tab completion
set ttyfast " we have a fast terminal
set noerrorbells " No error bells please
set shell=bash
set fileformats=unix
set ff=unix
filetype on " Enable filetype detection
filetype indent on " Enable filetype-specific indenting
filetype plugin on " Enable filetype-specific plugins
set wildmode=longest:full
set wildmenu " menu has tab completion
let maplocalleader=',' " all my macros start with ,
set laststatus=2
" searching
set incsearch " incremental search
set ignorecase " search ignoring case
set hlsearch " highlight the search
set showmatch " show matching bracket
set diffopt=filler,iwhite " ignore all whitespace and sync
" backup
set backup
set backupdir=~/.vim_backup
set viminfo=%100,'100,/100,h,\"500,:100,n~/.viminfo
"set viminfo='100,f1
" spelling
if v:version >= 700
" Enable spell check for text files
autocmd BufNewFile,BufRead *.txt setlocal spell spelllang=en
endif
" mappings
" toggle list mode
nmap <LocalLeader>tl :set list!<cr>
" toggle paste mode
nmap <LocalLeader>pp :set paste!<cr>
Sometimes the simplest things are the most valuable. The 2 lines in my .vimrc that are totally indispensable:
nore ; :
nore , ;
Misc. settings:
Turn off annoying error bells:
set noerrorbells
set visualbell
set t_vb=
Make cursor move as expected with wrapped lines:
inoremap <Down> <C-o>gj
inoremap <Up> <C-o>gk
Lookup ctags "tags" file up the directory, until one is found:
set tags=tags;/
Display SCons files wiith Python syntax:
autocmd BufReadPre,BufNewFile SConstruct set filetype=python
autocmd BufReadPre,BufNewFile SConscript set filetype=python
I'm not the most advanced vim'er in the world, but here's a few I've picked up
function! Mosh_Tab_Or_Complete()
if col('.')>1 && strpart( getline('.'), col('.')-2, 3 ) =~ '^\w'
return "\<C-N>"
else
return "\<Tab>"
endfunction
inoremap <Tab> <C-R>=Mosh_Tab_Or_Complete()<CR>
Makes the tab-autocomplete figure out whether you want to place a word there or an actual
tab(4 spaces).
map cc :.,$s/^ *//<CR>
Remove all opening whitespace from here to the end of the file. For some reason I find this useful a lot.
set nu!
set nobackup
Show line numbers and don't create those annoying backup files. I've never restored anything from an old backup anyways.
imap ii <C-[>
While in insert, press i twice to go to command mode. I've never come across a word or variable with 2 i's in a row, and this way I don't have to have my fingers leave the home row or press multiple keys to switch back and forth.
My heavily commented vimrc, with readline-esque (emacs) keybindings:
if version >= 700
"------ Meta ------"
" clear all autocommands! (this comment must be on its own line)
autocmd!
set nocompatible " break away from old vi compatibility
set fileformats=unix,dos,mac " support all three newline formats
set viminfo= " don't use or save viminfo files
"------ Console UI & Text display ------"
set cmdheight=1 " explicitly set the height of the command line
set showcmd " Show (partial) command in status line.
set number " yay line numbers
set ruler " show current position at bottom
set noerrorbells " don't whine
set visualbell t_vb= " and don't make faces
set lazyredraw " don't redraw while in macros
set scrolloff=5 " keep at least 5 lines around the cursor
set wrap " soft wrap long lines
set list " show invisible characters
set listchars=tab:>·,trail:· " but only show tabs and trailing whitespace
set report=0 " report back on all changes
set shortmess=atI " shorten messages and don't show intro
set wildmenu " turn on wild menu :e <Tab>
set wildmode=list:longest " set wildmenu to list choice
if has('syntax')
syntax on
" Remember that rxvt-unicode has 88 colors by default; enable this only if
" you are using the 256-color patch
if &term == 'rxvt-unicode'
set t_Co=256
endif
if &t_Co == 256
colorscheme xoria256
else
colorscheme peachpuff
endif
endif
"------ Text editing and searching behavior ------"
set nohlsearch " turn off highlighting for searched expressions
set incsearch " highlight as we search however
set matchtime=5 " blink matching chars for .x seconds
set mouse=a " try to use a mouse in the console (wimp!)
set ignorecase " set case insensitivity
set smartcase " unless there's a capital letter
set completeopt=menu,longest,preview " more autocomplete <Ctrl>-P options
set nostartofline " leave my cursor position alone!
set backspace=2 " equiv to :set backspace=indent,eol,start
set textwidth=80 " we like 80 columns
set showmatch " show matching brackets
set formatoptions=tcrql " t - autowrap to textwidth
" c - autowrap comments to textwidth
" r - autoinsert comment leader with <Enter>
" q - allow formatting of comments with :gq
" l - don't format already long lines
"------ Indents and tabs ------"
set autoindent " set the cursor at same indent as line above
set smartindent " try to be smart about indenting (C-style)
set expandtab " expand <Tab>s with spaces; death to tabs!
set shiftwidth=4 " spaces for each step of (auto)indent
set softtabstop=4 " set virtual tab stop (compat for 8-wide tabs)
set tabstop=8 " for proper display of files with tabs
set shiftround " always round indents to multiple of shiftwidth
set copyindent " use existing indents for new indents
set preserveindent " save as much indent structure as possible
filetype plugin indent on " load filetype plugins and indent settings
"------ Key bindings ------"
" Remap broken meta-keys that send ^[
for n in range(97,122) " ASCII a-z
let c = nr2char(n)
exec "set <M-". c .">=\e". c
exec "map \e". c ." <M-". c .">"
exec "map! \e". c ." <M-". c .">"
endfor
""" Emacs keybindings
" first move the window command because we'll be taking it over
noremap <C-x> <C-w>
" Movement left/right
noremap! <C-b> <Left>
noremap! <C-f> <Right>
" word left/right
noremap <M-b> b
noremap! <M-b> <C-o>b
noremap <M-f> w
noremap! <M-f> <C-o>w
" line start/end
noremap <C-a> ^
noremap! <C-a> <Esc>I
noremap <C-e> $
noremap! <C-e> <Esc>A
" Rubout word / line and enter insert mode
noremap <C-w> i<C-w>
noremap <C-u> i<C-u>
" Forward delete char / word / line and enter insert mode
noremap! <C-d> <C-o>x
noremap <M-d> dw
noremap! <M-d> <C-o>dw
noremap <C-k> Da
noremap! <C-k> <C-o>D
" Undo / Redo and enter normal mode
noremap <C-_> u
noremap! <C-_> <C-o>u<Esc><Right>
noremap! <C-r> <C-o><C-r><Esc>
" Remap <C-space> to word completion
noremap! <Nul> <C-n>
" OS X paste (pretty poor implementation)
if has('mac')
noremap √ :r!pbpaste<CR>
noremap! √ <Esc>√
endif
""" screen.vim REPL: http://github.com/ervandew/vimfiles
" send paragraph to parallel process
vmap <C-c><C-c> :ScreenSend<CR>
nmap <C-c><C-c> mCvip<C-c><C-c>`C
imap <C-c><C-c> <Esc><C-c><C-c><Right>
" set shell region height
let g:ScreenShellHeight = 12
"------ Filetypes ------"
" Vimscript
autocmd FileType vim setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4
" Shell
autocmd FileType sh setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4
" Lisp
autocmd Filetype lisp,scheme setlocal equalprg=~/.vim/bin/lispindent.lisp expandtab shiftwidth=2 tabstop=8 softtabstop=2
" Ruby
autocmd FileType ruby setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2
" PHP
autocmd FileType php setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4
" X?HTML & XML
autocmd FileType html,xhtml,xml setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2
" CSS
autocmd FileType css setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4
" JavaScript
" autocmd BufRead,BufNewFile *.json setfiletype javascript
autocmd FileType javascript setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2
let javascript_enable_domhtmlcss=1
"------ END VIM-500 ------"
endif " version >= 500
syntax on
set cindent
set ts=4
set sw=4
set backspace=2
set laststatus=2
set nohlsearch
set modeline
set modelines=3
set ai
map Q gq
set vb t_vb=
set nowrap
set ss=5
set is
set scs
set ru
map <F2> <Esc>:w<CR>
map! <F2> <Esc>:w<CR>
map <F10> <Esc>:qa<CR>
map! <F10> <Esc>:qa<CR>
map <F9> <Esc>:wqa<CR>
map! <F9> <Esc>:wqa<CR>
inoremap <s-up> <Esc><c-w>W<Ins>
inoremap <s-down> <Esc><c-w>w<Ins>
nnoremap <s-up> <c-w>W
nnoremap <s-down> <c-w>w
" Fancy middle-line <CR>
inoremap <C-CR> <Esc>o
nnoremap <C-CR> o
" This is the way I like my quotation marks and various braces
inoremap '' ''<Left>
inoremap "" ""<Left>
inoremap () ()<Left>
inoremap <> <><Left>
inoremap {} {}<Left>
inoremap [] []<Left>
inoremap () ()<Left>
" Quickly set comma or semicolon at the end of the string
inoremap ,, <End>,
inoremap ;; <End>;
au FileType python inoremap :: <End>:
au FileType perl,python set foldlevel=0
au FileType perl,python set foldcolumn=4
au FileType perl,python set fen
au FileType perl set fdm=syntax
au FileType python set fdm=indent
au FileType perl,python set fdn=4
au FileType perl,python set fml=10
au FileType perl,python set fdo=block,hor,mark,percent,quickfix,search,tag,undo,search
au FileType perl,python abbr sefl self
au FileType perl abbr sjoft shift
au FileType perl abbr DUmper Dumper
function! ToggleNumberRow()
if !exists("g:NumberRow") || 0 == g:NumberRow
let g:NumberRow = 1
call ReverseNumberRow()
else
let g:NumberRow = 0
call NormalizeNumberRow()
endif
endfunction
" Reverse the number row characters
function! ReverseNumberRow()
" map each number to its shift-key character
inoremap 1 !
inoremap 2 #
inoremap 3 #
inoremap 4 $
inoremap 5 %
inoremap 6 ^
inoremap 7 &
inoremap 8 *
inoremap 9 (
inoremap 0 )
inoremap - _
inoremap 90 ()<Left>
" and then the opposite
inoremap ! 1
inoremap # 2
inoremap # 3
inoremap $ 4
inoremap % 5
inoremap ^ 6
inoremap & 7
inoremap * 8
inoremap ( 9
inoremap ) 0
inoremap _ -
endfunction
" DO the opposite to ReverseNumberRow -- give everything back
function! NormalizeNumberRow()
iunmap 1
iunmap 2
iunmap 3
iunmap 4
iunmap 5
iunmap 6
iunmap 7
iunmap 8
iunmap 9
iunmap 0
iunmap -
"------
iunmap !
iunmap #
iunmap #
iunmap $
iunmap %
iunmap ^
iunmap &
iunmap *
iunmap (
iunmap )
iunmap _
inoremap () ()<Left>
endfunction
"call ToggleNumberRow()
nnoremap <M-n> :call ToggleNumberRow()<CR>
" Add use <CWORD> at the top of the file
function! UseWord(word)
let spec_cases = {'Dumper': 'Data::Dumper'}
let my_word = a:word
if has_key(spec_cases, my_word)
let my_word = spec_cases[my_word]
endif
let was_used = search("^use.*" . my_word, "bw")
if was_used > 0
echo "Used already"
return 0
endif
let last_use = search("^use", "bW")
if 0 == last_use
last_use = search("^package", "bW")
if 0 == last_use
last_use = 1
endif
endif
let use_string = "use " . my_word . ";"
let res = append(last_use, use_string)
return 1
endfunction
function! UseCWord()
let cline = line(".")
let ccol = col(".")
let ch = UseWord(expand("<cword>"))
normal mu
call cursor(cline + ch, ccol)
endfunction
function! GetWords(pattern)
let cline = line(".")
let ccol = col(".")
call cursor(1,1)
let temp_dict = {}
let cpos = searchpos(a:pattern)
while cpos[0] != 0
let temp_dict[expand("<cword>")] = 1
let cpos = searchpos(a:pattern, 'W')
endwhile
call cursor(cline, ccol)
return keys(temp_dict)
endfunction
" Append the list of words, that match the pattern after cursor
function! AppendWordsLike(pattern)
let word_list = sort(GetWords(a:pattern))
call append(line("."), word_list)
endfunction
nnoremap <F7> :call UseCWord()<CR>
" Useful to mark some code lines as debug statements
function! MarkDebug()
let cline = line(".")
let ctext = getline(cline)
call setline(cline, ctext . "##_DEBUG_")
endfunction
" Easily remove debug statements
function! RemoveDebug()
%g/#_DEBUG_/d
endfunction
au FileType perl,python inoremap <M-d> <Esc>:call MarkDebug()<CR><Ins>
au FileType perl,python inoremap <F6> <Esc>:call RemoveDebug()<CR><Ins>
au FileType perl,python nnoremap <F6> :call RemoveDebug()<CR>
" end Perl settings
nnoremap <silent> <F8> :TlistToggle<CR>
inoremap <silent> <F8> <Esc>:TlistToggle<CR><Esc>
function! AlwaysCD()
if bufname("") !~ "^scp://" && bufname("") !~ "^sftp://" && bufname("") !~ "^ftp://"
lcd %:p:h
endif
endfunction
autocmd BufEnter * call AlwaysCD()
function! DeleteRedundantSpaces()
let cline = line(".")
let ccol = col(".")
silent! %s/\s\+$//g
call cursor(cline, ccol)
endfunction
au BufWrite * call DeleteRedundantSpaces()
set nobackup
set nowritebackup
set cul
colorscheme evening
autocmd FileType python set formatoptions=wcrq2l
autocmd FileType python set inc="^\s*from"
autocmd FileType python so /usr/share/vim/vim72/indent/python.vim
autocmd FileType c set si
autocmd FileType mail set noai
autocmd FileType mail set ts=3
autocmd FileType mail set tw=78
autocmd FileType mail set shiftwidth=3
autocmd FileType mail set expandtab
autocmd FileType xslt set ts=4
autocmd FileType xslt set shiftwidth=4
autocmd FileType txt set ts=3
autocmd FileType txt set tw=78
autocmd FileType txt set expandtab
" Move cursor together with the screen
noremap <c-j> j<c-e>
noremap <c-k> k<c-y>
" Better Marks
nnoremap ' `
Some fixes for common typos have saved me a surprising amount of time:
:command WQ wq
:command Wq wq
:command W w
:command Q q
iab anf and
iab adn and
iab ans and
iab teh the
iab thre there
I didn't realize how many of my 3200 .vimrc lines were just for my quirky needs and would be pretty uninspiring to list here. But maybe that's why Vim is so useful...
iab AlP ABCDEFGHIJKLMNOPQRSTUVWXYZ
iab MoN January February March April May June July August September October November December
iab MoO Jan Feb Mar Apr May Jun Jul Aug Sep Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
iab NuM 12345678901234567890123456789012345678901234567890123456789012345678901234567890
iab RuL ----+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0
" Highlight every other line
map ,<Tab> :set hls<CR>/\\n.*\\n/<CR>
" This is for working across multiple xterms and/or gvims
" Transfer/read and write one block of text between vim sessions (capture whole line):
" Write
nmap ;w :. w! ~/.vimxfer<CR>
" Read
nmap ;r :r ~/.vimxfer<CR>
" Append
nmap ;a :. w! >>~/.vimxfer<CR>
My 242-line .vimrc is not that interesting, but since nobody mentioned it, I felt like I must share the two most important mappings that have enhanced my workflow besides the default mappings:
map <C-j> :bprev<CR>
map <C-k> :bnext<CR>
set hidden " this will go along
Seriously, switching buffers is the thing to do very often. Windows, sure, but everything doesn't fit the screen so nicely.
Similar set of maps for quick browsing of errors (see quickfix) and grep results:
map <C-n> :cn<CR>
map <C-m> :cp<CR>
Simple, effortless and efficient.
set nobackup
set nocp
set tabstop=4
set shiftwidth=4
set et
set ignorecase
set ai
set ruler
set showcmd
set incsearch
set dir=$temp " Make swap live in the %TEMP% directory
syn on
" Load the color scheme
colo inkpot
I use cscope from within vim (making great use of the multiple buffers). I use control-K to initiate most of the commands (stolen from ctags as I recall). Also, I've already generated the .cscope.out file.
if has("cscope")
set cscopeprg=/usr/local/bin/cscope
set cscopetagorder=0
set cscopetag
set cscopepathcomp=3
set nocscopeverbose
cs add .cscope.out
set csverb
"
" cscope find
"
" 0 or s: Find this C symbol
" 1 or d: Find this definition
" 2 or g: Find functions called by this function
" 3 or c: Find functions calling this function
" 4 or t: Find assignments to
" 6 or e: Find this egrep pattern
" 7 or f: Find this file
" 8 or i: Find files #including this file
"
map ^Ks :cs find 0 <C-R>=expand("<cword>")<CR><CR>
map ^Kd :cs find 1 <C-R>=expand("<cword>")<CR><CR>
map ^Kg :cs find 2 <C-R>=expand("<cword>")<CR><CR>
map ^Kc :cs find 3 <C-R>=expand("<cword>")<CR><CR>
map ^Kt :cs find 4 <C-R>=expand("<cword>")<CR><CR>
map ^Ke :cs find 6 <C-R>=expand("<cword>")<CR><CR>
map ^Kf :cs find 7 <C-R>=expand("<cfile>")<CR><CR>
map ^Ki :cs find 8 <C-R>=expand("%")<CR><CR>
endif
I keep my vimrc file up on github. You can find it here:
http://github.com/developernotes/vim-setup/tree/master
I'm on OS X, so some of these might have better defaults on other platforms, but regardless:
syntax on
set tabstop=4
set expandtab
set shiftwidth=4
map = }{!}fmt^M}
map + }{!}fmt -p '> '^M}
set showmatch
= is for reformatting normal paragraphs. + is for reformatting paragraphs in quoted emails. showmatch is for flashing the matching parenthesis/bracket when I type a close parenthesis or bracket.
Use the first available 'tags' file in the directory tree:
:set tags=tags;/
Left and right are for switching buffers, not moving the cursor:
map <right> <ESC>:bn<RETURN>
map <left> <ESC>:bp<RETURN>
Disable search highlighting with a single keypress:
map - :nohls<cr>
set tabstop=4 softtabstop=4 shiftwidth=4 expandtab autoindent cindent
set encoding=utf-8 fileencoding=utf-8
set nobackup nowritebackup noswapfile autoread
set number
set hlsearch incsearch ignorecase smartcase
if has("gui_running")
set lines=35 columns=140
colorscheme ir_black
else
colorscheme darkblue
endif
" bash like auto-completion
set wildmenu
set wildmode=list:longest
inoremap <C-j> <Esc>
" for lusty explorer
noremap glr \lr
noremap glf \lf
noremap glb \lb
" use ctrl-h/j/k/l to switch between splits
map <c-j> <c-w>j
map <c-k> <c-w>k
map <c-l> <c-w>l
map <c-h> <c-w>h
" Nerd tree stuff
let NERDTreeIgnore = ['\.pyc$', '\.pyo$']
noremap gn :NERDTree<Cr>
" cd to the current file's directory
noremap gc :lcd %:h<Cr>
Put this in your vimrc:
imap <C-l> <Space>=><Space>
and never think about typing a hashrocket again. Yes, I know you don't need to in Ruby 1.9. But never mind that.
My full vimrc is here.
Well, you'll have to scavenge my configs yourself. Have fun. Mostly it's just my desired setup, including mappings and random syntax-relevant stuff, as well as folding setup and some plugin configuration, a tex-compilation parser etc.
BTW, something I found extremely useful is "highlight word under cursor":
highlight flicker cterm=bold ctermfg=white
au CursorMoved <buffer> exe 'match flicker /\V\<'.escape(expand('<cword>'), '/').'\>/'
Note that only cterm and termfg are used, because I don't use gvim. If you want that to work in gvim just replac them with gui and guifg, respectively.
I've tried to keep my .vimrc as generally useful as possible.
A handy trick in there is a handler for .gpg files to edit them securely:
au BufNewFile,BufReadPre *.gpg :set secure vimi= noswap noback nowriteback hist=0 binary
au BufReadPost *.gpg :%!gpg -d 2>/dev/null
au BufWritePre *.gpg :%!gpg -e -r 'name#email.com' 2>/dev/null
au BufWritePost *.gpg u
1) I like a statusline (with the filename, ascii value (decimal), hex value, and the standard lines, cols, and %):
set statusline=%t%h%m%r%=[%b\ 0x%02B]\ \ \ %l,%c%V\ %P
" Always show a status line
set laststatus=2
"make the command line 1 line high
set cmdheight=1
2) I also like mappings for split windows.
" <space> switches to the next window (give it a second)
" <space>n switches to the next window
" <space><space> switches to the next window and maximizes it
" <space>= Equalizes the size of all windows
" + Increases the size of the current window
" - Decreases the size of the current window
:map <space> <c-W>w
:map <space>n <c-W>w
:map <space><space> <c-W>w<c-W>_
:map <space>= <c-W>=
if bufwinnr(1)
map + <c-W>+
map - <c-W>-
endif
There isn't much actually in my .vimrc (even if it has 850 lines). Mostly settings and a few common and simple mappings that I was too lazy to extract into plugins.
If you mean "template-files" by "auto-classes", I'm using a template-expander plugin -- on this same site, you'll find the ftplugins I've defined for C&C++ editing, some may be adapted to C# I guess.
Regarding the refactoring aspect, there is a tip dedicated to this subject on http://vim.wikia.com ; IIRC the example code is for C#. It inspired me a refactoring plugin that still needs of lot of work (it needs to be refactored actually).
You should have a look at the archives of vim mailing-list, specially the subjects about using vim as an effective IDE. Don't forget to have a look at :make, tags, ...
HTH,
My .vimrc includes (among other, more usefull things) the following line:
set statusline=%2*%n\|%<%*%-.40F%2*\|\ %2*%M\ %3*%=%1*\ %1*%2.6l%2*x%1*%1.9(%c%V%)%2*[%1*%P%2*]%1*%2B
I got bored while learning for my high school finals.
Here is my .vimrc. I use Gvim 7.2
set guioptions=em
set showtabline=2
set softtabstop=2
set shiftwidth=2
set tabstop=2
" Use spaces instead of tabs
set expandtab
set autoindent
" Colors and fonts
colorscheme inkpot
set guifont=Consolas:h11:cANSI
"TAB navigation like firefox
:nmap <C-S-tab> :tabprevious<cr>
:nmap <C-tab> :tabnext<cr>
:imap <C-S-tab> <ESC>:tabprevious<cr>i
:imap <C-tab> <ESC>:tabnext<cr>i
:nmap <C-t> :tabnew<cr>
:imap <C-t> <ESC>:tabnew<cr>i
:map <C-w> :tabclose<cr>
" No Backups and line numbers
set nobackup
set number
set nuw=6
" swp files are saved to %Temp% folder
set dir=$temp
" sets the default size of gvim on open
set lines=40 columns=90
What's in my .vimrc?
ngn#macavity:~$ cat .vimrc
" This file intentionally left blank
The real config files lie under ~/.vim/ :)
And most of the stuff there is parasiting on other people's efforts, blatantly adapted from vim.org to my editing advantage.

Resources