VIM function to insert timestamp - vim

Someone in a previous question suggested the following for adding timestamps to VIM:
nmap <F3> a<C-R>=strftime("%Y-%m-%d %a %I:%M %p")<CR><Esc>
imap <F3> <C-R>=strftime("%Y-%m-%d %a %I:%M %p")<CR>
Instead of using F3, I'd like to insert the timestamp by executing a function instead. For example, typing :Now.
Unfortunately, I don't grok VIM scripting. Can someone help?

:Now is not a function, it is a command. You can create command out of first mapping with the following code:
command -nargs=0 -bar Now execute "normal! a\<C-R>=strftime(\"%Y-%m-%d %a %I:%M %p\")\<CR>"

" if not has 'Last Change' in first 5 lines
fun! InsertChangeLog()
let l:flag=0
for i in range(1,5)
if getline(i) !~ '.*Last Change.*'
let l:flag = l:flag + 1
endif
endfor
if l:flag >= 5
normal(1G)
call append(0, "File: <+Description+>")
call append(1, "Created: " . strftime("%a %d/%b/%Y hs %H:%M"))
call append(2, "Last Change: " . strftime("%a %d/%b/%Y hs %H:%M"))
call append(3, "author: <+digite seu nome+>")
call append(4, "site: <+your website+>")
call append(5, "twitter: <+your twitter here+>")
normal gg
endif
endfun
" map F4 to insert change log
map <special> <F4> <esc>:call InsertChangeLog()<cr>
" update changefile log
" http://tech.groups.yahoo.com/group/vim/message/51005
" automaticaly update Last Change whitout change jump list
" see :h keepjumps
fun! LastChange()
let _s=#/
let l = line(".")
let c = col(".")
if line("$") >= 5
1,5s/\s*Last Change:\s*\zs.*/\="" . strftime("%Y %b %d %X")/ge
endif
let #/=_s
call cursor(l, c)
endfun
autocmd BufWritePre * keepjumps call LastChange()
" place holders snippets - change map !!!
" File Templates
" --------------
" <leader>j jumps to the next marker
" iabbr <buffer> for for <+i+> in <+intervalo+>:<cr><tab><+i+>
function! LoadFileTemplate()
"silent! 0r ~/.vim/templates/%:e.tmpl
syn match vimTemplateMarker "<+.\++>" containedin=ALL
hi vimTemplateMarker guifg=#67a42c guibg=#112300 gui=bold
endfunction
function! JumpToNextPlaceholder()
let old_query = getreg('/')
echo search("<+.\\++>")
exec "norm! c/+>/e\<CR>"
call setreg('/', old_query)
endfunction
autocmd BufNewFile * :call LoadFileTemplate()
nnoremap <leader>j :call JumpToNextPlaceholder()<CR>a
inoremap <leader>j <ESC>:call JumpToNextPlaceholder()<CR>a

Related

Manual vim code folds keep moving

I prefer to make my code folds manually. However, I've noticed that the folds move after I
Make the fold using zf
Make some deletes/inserts after/below the code fold
The folds "move" in the sense that if 51 lines were folded, after movement only 50 lines are now folded. This makes it so that part of the code that was folded is no longer in the fold and now just looks like a randomly placed piece of code. I often have to delete the moved fold and do a refold.
Any ideas on how to fix this? Please let me know if this didn't make any sense or if you can't replicate this behavior.
set nocompatible " required
filetype off " required
" ================================================================="
" ================================================================="
" ==================== Begin my added plugins ====================="
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'VundleVim/Vundle.vim'
Plugin 'vim-syntastic/syntastic'
Plugin 'luochen1990/rainbow'
Plugin 'godlygeek/tabular'
Plugin 'garbas/vim-snipmate'
Plugin 'MarcWeber/vim-addon-mw-utils'
Plugin 'tomtom/tlib_vim'
Plugin 'honza/vim-snippets'
Plugin 'aperezdc/vim-template'
Plugin 'tpope/tpope-vim-abolish'
Plugin 'Raimondi/delimitMate'
Plugin 'tpope/vim-repeat'
call vundle#end()
filetype plugin indent on
" ================================================================="
" ================================================================="
" ===================== End my added plugins ======================"
if v:lang =~ "utf8$" || v:lang =~ "UTF-8$"
set fileencodings=ucs-bom,utf-8,latin1
endif
set bs=indent,eol,start " allow backspacing over everything in insert mode
set ai " always set autoindenting on
set viminfo='20,\"50 " read/write a .viminfo file, don't store more than 50 lines of registers
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
" Only do this part when compiled with support for autocommands
if has("autocmd")
augroup fedora
autocmd!
" In text files, always limit the width of text to 78 characters
" autocmd BufRead *.txt set tw=78
" When editing a file, always jump to the last cursor position
autocmd BufReadPost *
\ if line("'\"") > 0 && line ("'\"") <= line("$") |
\ exe "normal! g'\"" |
\ endif
" don't write swapfile on most commonly used directories for NFS mounts or USB sticks
autocmd BufNewFile,BufReadPre /media/*,/run/media/*,/mnt/* set directory=~/tmp,/var/tmp,/tmp
" start with spec file template
autocmd BufNewFile *.spec 0r /usr/share/vim/vimfiles/template.spec
" auto-source the vimrc upon writing to the file
autocmd bufwritepost vimrc source %
augroup END
endif
if has("cscope") && filereadable("/usr/bin/cscope")
set csprg=/usr/bin/cscope
set csto=0
set cst
set nocsverb
" add any database in current directory
if filereadable("cscope.out")
cs add $PWD/cscope.out
" else add database pointed to by environment
elseif $CSCOPE_DB != ""
cs add $CSCOPE_DB
endif
set csverb
endif
syntax enable
" ================================================================="
" ================================================================="
" ============== Begin additions for Syntastic plugin ============="
let &shellpipe = '2>&1| tee'
let &shellredir = '>%s 2>&1'
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_enable_signs=1
let g:syntastic_check_on_wq = 0
"let g:syntastic_auto_loc_list = 2
"let g:syntastic_check_on_open = 1
"let g:syntastic_check_on_wq = 0
"let g:syntastic_enable_balloons = 0
"let g:syntastic_error_symbol = '✗'
"let g:syntastic_ignore_files = ['\.min\.js$', '\.min\.css$']
"let g:syntastic_loc_list_height = 5
"let g:syntastic_warning_symbol = '✗'
"let g:syntastic_style_error_symbol = '∆'
"let g:syntastic_style_warning_symbol = '∆'
" shortcut command for toggling syntastic mode (useful for when I'm just writing test code)
fun! s:toggle_syntastic()
call SyntasticToggleMode()
endfun
command! STM :call s:toggle_syntastic()
" ================================================================="
" ================================================================="
" =========== Begin additions for Rainbow_parens plugin ==========="
" set to zero and use :RainbowToggle to switch between modes
let g:rainbow_active = 1
" ================================================================="
" ================================================================="
" =========== Begin additions for Tabular plugin ==========="
vnoremap ;t :Tabularize /
" ================================================================="
" ================================================================="
" =========== Begin additions for SnipMate plugin ==========="
let g:snippet_version = 1
" ================================================================="
" ================================================================="
" ============== Begin additions for Templates plugin ============="
" see :h template.txt
" let g:templates_user_variables = [
" \ ['FULLPATH', 'GetFullPath'],
" \ ]
"
" function! GetFullPath()
" return expand('%:p')
" endfunction
" ================================================================="
" ================================================================="
" ================== Begin my 'set' vimrc things =================="
" Show (partial) command in status line
set showcmd
" Do case insensitive matching, smart case matching, don't wrap back to the top after searching
set ignorecase
set smartcase
set nowrapscan
set incsearch
" Automatically save before commands like :make
set autowrite
" Hide buffers when they are abandoned
set hidden
" set tab length, indentation length, auto indent
set tabstop=4
set shiftwidth=4
set autoindent
" disable swap file generation
set noswapfile
" change the orientation of the windows when using :split and :vs
set splitbelow
set splitright
" save state of original code folds, don't open code folds when doing searches
autocmd BufWinLeave *.* mkview
autocmd BufWinEnter *.* silent loadview
set foldopen-=search
set viewoptions=folds,cursor
" auto comments for /* (javadoc style comments)
set comments=sl:/*,mb:\ *,elx:\ */
" lets the tags file to be in a separate directory from the source code
" basically does the following:
" goes up one directory at a time until it finds a file called '.tags'
set tags=.tags;/
" set manual fold method, min number of lines to make a fold = 1
set fdm=manual
set fml=1
" fold method based on file syntax
" fold level = 2 for .java = 1 for .c
" min fold level = 0 for folding single lines
"set fdm=syntax
"set fml=0
"if &filetype == 'java'
" set fdn=2
"elseif &filetype == 'c'
" set fdn=1
"endif
" searches down into subfolders
" provides tab-completion for all file-related tasks
set path+=**
" display all matching files when you tab-complete
set wildmenu
" tweaks for file browsing
let g:netrw_browse_split=4 " open in prior window
let g:netrw_altv=1 " open splits to the right
let g:netrw_liststyle=3 " tree view
" set matching parenthesis/brace/bracket to be underlined
hi MatchParen cterm=underline ctermbg=none ctermfg=none
" make the vim tab bar look prettier
hi TabLineFill ctermfg=Black ctermbg=Black
hi TabLine ctermfg=Blue ctermbg=Black
hi TabLineSel ctermfg=Black ctermbg=Yellow
hi Title ctermfg=Black ctermbg=Yellow
" set variable 'g:os' according to development environment
if !exists('g:os')
if has('win32') || has('win16')
let g:os = 'Windows'
else
let g:os = substitute(system('uname'), '\n', '', '')
endif
endif
" a godsend that disables that stupidly annoying beep/bell once and for all
if g:os =~ 'CYGWIN'
set belloff=all
endif
" prevent ubuntu from outputting garbage characters
if g:os =~ 'Linux'
set t_RV=
endif
" make the clipboard the default register
if has('unnamedplus')
set clipboard=unnamed,unnamedplus
else
set clipboard=unnamed
endif
" ================================================================="
" ================================================================="
" =============== Begin my 'nnoremaps' vimrc things ==============="
" typing '' now also centers the screen
nnoremap '' ''zz
" map the jump-to-mark command 'm so that the
" command centers the screen upon jumping
nnoremap 'm 'mzz
"" press % to visually highlight in-between brace/bracket/parentheses
noremap % v%
" press CTRL-j/CTRL-k to go down/up half a page, respectively
noremap <C-j> <C-D>
noremap <C-k> <C-U>
" capital K enters a linefeed while maintaining normal mode
nnoremap K i<CR><ESC>
" use CTRL-h and CTRL-L to switch between Vim tabs
nnoremap <C-h> gT
inoremap <C-h> <ESC>gT
nnoremap <C-l> gt
inoremap <C-l> <ESC>gt
" use , to repeat the last find command --> use shift, to go the other way
nnoremap , ;
vnoremap , ;
nnoremap < ,
" remap the normal paste to align the pasted block with the surrounded text
nnoremap p ]p
nnoremap P ]P
" remap yb to not move the cursor backwards (repositioning the cursor was annoying)
nnoremap yb ybw
" remap CTRL-n to move to the next line that has a compile error"
nnoremap <C-n> :cn<CR>
" remap CTRL-p to move to the previous line that has a compile error"
" NOTE: can also map this to CTRL-N
nnoremap <C-p> :cp<CR>
" mappings for easily deleting the surrounding brackets/parentheses
" ==========================================================================================================
nnoremap <silent> <Plug>Map_df( dt(me%x`ex:silent! call repeat#set("\<plug>Map_df(", v:count)<cr>
nmap df( <Plug>Map_df(
nnoremap <silent> <Plug>Map_d( me%x`ex:silent! call repeat#set("\<Plug>Map_d(", v:count)<CR>
nmap d( <Plug>Map_d(`e
nnoremap <silent> <Plug>Map_df[ dt[me%x`ex:silent! call repeat#set("\<Plug>Map_df[", v:count)<CR>
nmap df[ <Plug>Map_df[`e
nnoremap <silent> <Plug>Map_d[ me%x`ex:silent! call repeat#set("\<Plug>Map_d[", v:count)<CR>
nmap d[ <Plug>Map_df[`e
" ==========================================================================================================
" mappings for easily changing the surrounding brackets/parentheses
" ==========================================================================================================
nnoremap <silent> <Plug>Map_cf( dt(me%x`exi:silent! call repeat#set("\<Plug>Map_cf(", v:count)<CR>
nmap cf( <Plug>Map_cf(`e
nnoremap <silent> <Plug>Map_c( %me%r(`er)%:silent! call repeat#set("\<Plug>Map_c(", v:count)<CR>
nmap c( <Plug>Map_c(`e
nnoremap <silent> <Plug>Map_cf[ dt[me%x`exi:silent! call repeat#set("\<Plug>Map_cf[", v:count)<CR>
nmap cf[ <Plug>Map_cf[`e
nnoremap <silent> <Plug>Map_c[ %me%r[`er]%:silent! call repeat#set("\<Plug>Map_c[", v:count)<CR>
nmap c[ <Plug>Map_c[`e
" ==========================================================================================================
" mappings for easily replacing the surrounding brackets/parentheses
" ==========================================================================================================
nnoremap <silent> <Plug>Map_r( %me%r(`er)%:silent! call repeat#set("\<Plug>Map_r(", v:count)<CR>
nmap r( <Plug>Map_r(`e
nnoremap <silent> <Plug>Map_r[ %me%r[`er]%:silent! call repeat#set("\<Plug>Map_r[", v:count)<CR>
nmap r[ <Plug>Map_r[`e
" ==========================================================================================================
" remap U to ~ for easier uppercasing/lowercasing
nnoremap U ~
" pressing Control-w then Control-c in split windows accidentally closes the window. I dislike this
nnoremap <C-w><C-c> <ESC>
" using 'x' will now put the 'cut' letter(s) in the black hole register "_
nnoremap x "_x
nnoremap X "_X
" using '' to will now put you at the (last cursor position) instead of the (last row your cursor was in)
nnoremap '' ``zz
" map Y to act the same as D & C
nnoremap Y y$
" ================================================================="
" ================================================================="
" =============== Begin my 'inoremaps' vimrc things ==============="
" autocomplete for matching brace (activated upon pressing enter)
if g:os =~ 'CYGWIN'
inoremap {<CR> {<TAB><CR>}<Esc><Esc>O
elseif g:os =~ 'Linux'
inoremap {<CR> {<CR>}<ESC>O
endif
" DUMBEST HACK EVER (but I'm so happy it works)
" normally pressing CTRL-c undoes your auto-indent on a blank line
" solutions to this is to make a new line that is auto-indented for you
" and then type some random character, delete it, then press CTRL-c
" so, that's exactly what this hack does
inoremap <C-c> l<BS><ESC>
" remap the paste function in insert mode to Control-p
inoremap <C-p> <C-R>*
" remap the autocomplete feature in vim to only look in the current file
inoremap <C-n> <C-x><C-n>
" remap the autocomplete feature for files to Control-m in insert mode
inoremap <C-k> <C-x><C-f>
" ================================================================="
" ================================================================="
" =============== Begin my 'vnoremaps' vimrc things ==============="
" easier uppercasing/lowercasing
vnoremap U ~
" so that your default register won't be overwritten when you paste over stuff in visual mode
xnoremap p "_dP
" ================================================================="
" ================================================================="
" ============== Begin some 'function' vimrc things ==============="
" now you can close the file, get back in, and still maintain the original undo tree
if has('persistent_undo')
set undolevels=5000
call system('mkdir ~/.vim/undo')
set undodir=~/.vim/undo
set undofile
endif
"=================================================================="
" toggle commented lines for #-style comments
function! ToggleComment_Py()
if matchstr(getline(line(".")),'^\s*\#.*$') == ''
:execute "s:^:# :"
else
:execute "s:^\s*# ::"
endif
endfunction
vnoremap ;# :call ToggleComment_Py()<CR>
nnoremap ;# :call ToggleComment_Py()<CR>
" toggle commented lines for "-style comments
function! ToggleComment_Vimrc()
if matchstr(getline(line(".")),'^\s*\".*$') == ''
:execute 's:^:" :'
else
:execute 's:^\s*" ::'
endif
endfunction
vnoremap ;" :call ToggleComment_Vimrc()<CR>
nnoremap ;" :call ToggleComment_Vimrc()<CR>
"=================================================================="
" reformat multiline if-statements into single line if-statements
fun! s:reformat(line1, line2)
" Remember line locs and numbers (bookkeeping)
execute 'normal!' 'me'
let l:before = line('$')
" Join the selected lines && put a newline before every 'else'
execute 'normal!' . (a:line2 - a:line1 + 1) . 'J'
execute 's/else/\relse/g'
" Recalculate the range && run Tabular
let l:line2 = a:line2 - (l:before - line('$'))
execute 'normal!' "V'e="
execute 'normal!' 'f(i '
execute a:line1 . ',' . l:line2 . 'Tabularize /{/'
endfun
command! -range Reformat :call s:reformat(<line1>, <line2>)
"=================================================================="
" unformat single line if-statements into multiline if-statements
fun! s:unformat(line1, line2)
" mark line one && keep track of lines selected
execute 'normal!' 'me'
let l:numDiff = a:line2 - a:line1 + 1
" delete extraneous white space
execute 'normal!' 'f dt(i '
let c = 0
while c < numDiff - 1
execute 'normal!' 'f)f dt{i '
execute 'normal!' 'j0w'
let c += 1
endwhile
execute 'normal!' 'f dt{i '
" Formatting to make the statements span multiple lines
execute 'normal!' "'e"
execute 'normal!' . (a:line2 - a:line1 + 1) . 'J'
execute 's/{ /{\r/g'
execute 'normal!' "'e"
let c = 0
while c < l:numDiff
execute 'normal!' 'j'
execute 's/}/\r}/g'
let c += 1
endwhile
execute 'normal!' "V'e="
endfun
command! -range Unformat :call s:unformat(<line1>, <line2>)
"=================================================================="
" a smarter delete operation (does not copy whitespace into registers)
" NOTE: this doesn't prevent copying whitespace using 'yy' or 'Vy'
" my assumption is that you wanted to copy the whitespace instead of deleting it
function! Smart_Delete_dd()
let temp = getreg('"', 1)
execute 'normal!' 'dd'
if matchstr(#", '\_s*') == #" " if just whitespace
call setreg('"', temp)
call setreg('*', temp)
call setreg('+', temp)
call setreg('0', temp)
endif
endfunction
nnoremap <silent> dd :call Smart_Delete_dd()<CR>
function! Smart_Delete_Vd() range
let temp = getreg('"', 1)
execute 'normal!' . (a:lastline - a:firstline + 1) . 'dd'
if matchstr(#", '\_s*') == #" " if just whitespace
call setreg('"', temp)
call setreg('*', temp)
call setreg('+', temp)
call setreg('0', temp)
endif
endfunction
vnoremap <silent> d :call Smart_Delete_Vd()<CR>
"=================================================================="
" insert the full path of the current file
fun! s:fullpath()
:put =expand('%:p')
endfun
command! FullPath :call s:fullpath()
" ================================================================="
" ================================================================="
" ================= Begin my custom ';' commands =================="
" use ;zf to fold all functions (in C and C++ and Java)
function! FoldFunctions()
:silent! execute "%g/^bool/normal! vf{%zf"
:silent! execute "%g/^boolean/normal! vf{%zf"
:silent! execute "%g/^int/normal! vf{%zf"
:silent! execute "%g/^double/normal! vf{%zf"
:silent! execute "%g/^void/normal! vf{%zf"
:silent! execute "%g/\tbool/normal! vf{%zf"
:silent! execute "%g/\tboolean/normal! vf{%zf"
:silent! execute "%g/\tint/normal! vf{%zf"
:silent! execute "%g/\tdouble/normal! vf{%zf"
:silent! execute "%g/\tvoid/normal! vf{%zf"
:silent! execute "%g/\tpublic/normal! vf{%zf"
:silent! execute "%g/\tprivate/normal! vf{%zf"
endfunc
nnoremap ;zf zE :call FoldFunctions()<CR><ESC>
" use ;n to toggle between number mode and relative number mode
function! NumberToggle()
if(&relativenumber == 1)
set nornu
set nonu
else
set rnu
set nu
endif
endfunc
nnoremap ;n :call NumberToggle()<CR>
set rnu
set nu
" use ;p to retain original indentation when pasting from another application
nnoremap ;p :set invpaste paste?<CR>
set showmode
" use ;w to remove trailing whitespace press ';w' (semicolon then 'w')
function! TrimWhitespace()
let l:save_cursor = getpos('.')
%s/\s\+$//e
call setpos('.', l:save_cursor)
endfunction
nnoremap ;w :call TrimWhitespace()<CR>
" use ;h to toggle highlighted search
nnoremap ;h :set hlsearch! hlsearch?<CR>
" use ;l to reload the file
nnoremap ;l :e<CR>
" use ;t and type a file name to open it in a VIM tab (:tabnew)
nnoremap ;t :tabnew
" use ;m to run the Makefile in the current directory (:make)
nnoremap ;m :make<CR>
" use ;s to source the vimrc file
nnoremap ;s :source $VIM/vimrc<CR>
" use ;f to format the file according to C++/Java style
nnoremap ;f :set expandtab! expandtab?<CR>gg=G''<ESC>
" use ;d to put deleted stuff in the black hole register "_
nnoremap ;d "_dd
vnoremap ;d "_d
" use ;j to jump from a function call to that function's definition
" use T to pop from the tag stack and go to that location
" use in conjuction with ctags
nnoremap ;j <C-]>zz
nnoremap T <C-t>zz
" use ;y to copy the current text file into the clipboard
nnoremap ;y myggvG$"*y'y
" use ;v to paste from the clipboard
nnoremap ;v "*p
" use ;zf to easily fold code that lies in between the braces
" v%zf<CR>
" use ;r in visual mode to replace the visually selected word
nnoremap ;r ye:%s/<C-F>pa//g<ESC>F/i
vnoremap ;r y:%s/<C-F>pa//g<ESC>F/i
" ================================================================="
" ================================================================="
" ================== Some nice things to remember ================="
" restore color scheme --> this is not actually mapped to something
" set filetype=____ (e.g. :set filetype=cpp)
" zipping files
" zip -r file_name.zip *
" specific things for filetypes --> actually don't do this --> see ~/.vim/after/ftplugin/
" au FileType python
" Don't wake up system with blinking cursor:
" http://www.linuxpowertop.org/known.php
let &guicursor = &guicursor . ",a:blinkon0"

A keybinding in vim has stopped and I'm stumped

I set up a key binding in my .vimrc to allow me to use silver-searcher for quick string searches across my apps.
Currently my .vimrc looks like this:
" .vimrc
set shell=/bin/sh
" load up pathogen and all bundles
call pathogen#infect()
call pathogen#helptags()
syntax on " show syntax highlighting
filetype plugin indent on
set autoindent " set auto indent
set ts=2 " set indent to 2 spaces
set shiftwidth=2
set expandtab " use spaces, not tab characters
set nocompatible " don't need to be compatible with old vim
set relativenumber " show relative line numbers
set showmatch " show bracket matches
set ignorecase " ignore case in search
set hlsearch " highlight all search matches
set cursorline " highlight current line
set smartcase " pay attention to case when caps are used
set incsearch " show search results as I type
set mouse=a " enable mouse support
set ttimeoutlen=100 " decrease timeout for faster insert with 'O'
set vb " enable visual bell (disable audio bell)
set ruler " show row and column in footer
set scrolloff=2 " minimum lines above/below cursor
set laststatus=2 " always show status bar
set list listchars=tab:»·,trail:· " show extra space characters
set nofoldenable " disable code folding
set clipboard=unnamed " use the system clipboard
set wildmenu " enable bash style tab completion
set wildmode=list:longest,full
runtime macros/matchit.vim " use % to jump between start/end of methods
" put git status, column/row number, total lines, and percentage in status
set statusline=%F%m%r%h%w\ %{fugitive#statusline()}\ [%l,%c]\ [%L,%p%%]
" set dark background and color scheme
set background=dark
colorscheme vimbrant
" set up some custom colors
highlight ColorColumn ctermbg=7
highlight ColorColumn guibg=Gray
" highlight the status bar when in insert mode
if version >= 700
au InsertEnter * hi StatusLine ctermfg=235 ctermbg=2
au InsertLeave * hi StatusLine ctermbg=240 ctermfg=12
endif
" highlight trailing spaces in annoying red
highlight ExtraWhitespace ctermbg=1 guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\#<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()
" set leader key to comma
let mapleader = ","
"silver searcher config
let g:ackprg = 'ag --nogroup --nocolor --column'
" ctrlp config
set runtimepath^=~/.vim/bundle/ctrlp.vim
let g:ctrlp_map = '<leader>f'
let g:ctrlp_max_height = 30
let g:ctrlp_working_path_mode = 0
let g:ctrlp_match_window_reversed = 0
" use silver searcher for ctrlp
let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
" unmap F1 help
nmap <F1> :echo<CR>
imap <F1> <C-o>:echo<CR>
" map . in visual mode
vnoremap . :norm.<cr>
" die hash rockets, die!
vnoremap <leader>h :s/:\(\w*\) *=>/\1:/g<cr>
" map markdown preview
map <leader>m :!open -a Marked %<cr><cr>
" map git commands
map <leader>b :Gblame<cr>
map <leader>l :!clear && git log -p %<cr>
map <leader>d :!clear && git diff %<cr>
" open gist after it's been created
let g:gist_open_browser_after_post = 1
" map Silver Searcher
map <leader>a :Ag!<space>
" search for word under cursor with Silver Searcher
map <leader>A :Ag! "<C-r>=expand('<cword>')<CR>"
" clear the command line and search highlighting
noremap <C-l> :nohlsearch<CR>
" toggle spell check with <F5>
map <F5> :setlocal spell! spelllang=en_us<cr>
imap <F5> <ESC>:setlocal spell! spelllang=en_us<cr>
" add :Plain command for converting text to plaintext
command! Plain execute "%s/’/'/ge | %s/[“”]/\"/ge | %s/—/-/ge"
" hint to keep lines short
if exists('+colorcolumn')
set colorcolumn=80
endif
" execute current file
map <leader>e :call ExecuteFile(expand("%"))<cr>
" execute file if we know how
function! ExecuteFile(filename)
:w
:silent !clear
if match(a:filename, '\.rb$') != -1
exec ":!ruby " . a:filename
elseif match(a:filename, '\.js$') != -1
exec ":!node " . a:filename
elseif match(a:filename, '\.sh$') != -1
exec ":!bash " . a:filename
else
exec ":!echo \"Don't know how to execute: \"" . a:filename
end
endfunction
" jump to last position in file
autocmd BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\ exe "normal g`\"" |
\ endif
" multi-purpose tab key (auto-complete)
function! InsertTabWrapper()
let col = col('.') - 1
if !col || getline('.')[col - 1] !~ '\k'
return "\<tab>"
else
return "\<c-p>"
endif
endfunction
inoremap <tab> <c-r>=InsertTabWrapper()<cr>
inoremap <s-tab> <c-n>
" rename current file, via Gary Bernhardt
function! RenameFile()
let old_name = expand('%')
let new_name = input('New file name: ', expand('%'))
if new_name != '' && new_name != old_name
exec ':saveas ' . new_name
exec ':silent !rm ' . old_name
redraw!
endif
endfunction
map <leader>n :call RenameFile()<cr>
function! RunTests(filename)
" Write the file and run tests for the given filename
:w
:silent !clear
if match(a:filename, '\.feature$') != -1
exec ":!bundle exec cucumber " . a:filename
elseif match(a:filename, '_test\.rb$') != -1
if filereadable("bin/testrb")
exec ":!bin/testrb " . a:filename
else
exec ":!ruby -Itest " . a:filename
end
else
if filereadable("Gemfile")
exec ":!bundle exec rspec --color " . a:filename
else
exec ":!rspec --color " . a:filename
end
end
endfunction
function! SetTestFile()
" set the spec file that tests will be run for.
let t:grb_test_file=#%
endfunction
function! RunTestFile(...)
if a:0
let command_suffix = a:1
else
let command_suffix = ""
endif
" run the tests for the previously-marked file.
let in_test_file = match(expand("%"), '\(.feature\|_spec.rb\|_test.rb\)$') != -1
if in_test_file
call SetTestFile()
elseif !exists("t:grb_test_file")
return
end
call RunTests(t:grb_test_file . command_suffix)
endfunction
function! RunNearestTest()
let spec_line_number = line('.')
call RunTestFile(":" . spec_line_number . " -b")
endfunction
" run test runner
map <leader>t :call RunTestFile()<cr>
map <leader>T :call RunNearestTest()<cr>
" show hidden files in NERDTree
let NERDTreeShowHidden=1
" show hidden files with ctrlp
let g:ctrlp_show_hidden = 1
" Mapping ESC in insert mode and command mode to double i
imap ii <C-[>
cmap ii <C-[>
What's weird is when I hit ,A it works perfectly, but ,a runs my test suite which is currently mapped to ,t.
I've been looking at this for hours and I think I'm just missing something dumb. I'm currently using macvim 7.4.52.

Vim delay with cw commands

I'm having an issue with some vim commands that replace words, specifically after movement commands like e, w and b.
Specifically, there is always a delay for cw, but not for ci" for example to change text within quotes.
Secondly, if I move three words forward, and type cw to change the third word without waiting a bit, it moves another word forward and cw's that one.
I've cut out a lot out of my Vimrc, and I can't really tell what might be causing the issue. Many times I end up doing a viw then c to change the word quickly, which doesn't make sense to me. Any insight into the issue would be fantastic.
Also, this is not system dependent, It's consistent across three different computers, nor is it syntax/filetype specific.
autocmd!
set nocompatible
filetype off
set rtp+=$HOME/.local/lib/python2.7/site-packages/powerline/bindings/vim
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()
Bundle 'gmarik/vundle'
Bundle 'nanotech/jellybeans.vim'
Bundle 'bling/vim-airline'
Bundle 'kchmck/vim-coffee-script'
Bundle 'bitc/vim-bad-whitespace'
Bundle 'scrooloose/nerdtree'
Bundle 'Lokaltog/vim-easymotion'
Bundle 'mileszs/ack.vim'
Bundle 'othree/html5.vim'
Bundle 'juvenn/mustache.vim'
Bundle 'yaymukund/vim-rabl'
Bundle 'int3/vim-extradite'
Bundle 'tpope/vim-fugitive'
Bundle 'tpope/vim-haml'
Bundle 'tpope/vim-repeat'
Bundle 'tpope/vim-endwise'
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-eunuch'
Bundle 'tpope/vim-surround'
Bundle 'tpope/vim-markdown'
Bundle 'kein/ctrlp.vim'
Bundle 'wincent/Command-T'
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" BASIC EDITING CONFIGURATION
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set nocompatible
" allow unsaved background buffers and remember marks/undo for them
set hidden
" remember more commands and search history
set nu
set history=10000
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set autoindent
set laststatus=2
set showmatch
set incsearch
set hlsearch
set t_Co=256
" make searches case-sensitive only if they contain upper-case characters
set ignorecase smartcase
" highlight current line
set cursorline
set cmdheight=1
set switchbuf=useopen
set showtabline=2
set winwidth=79
" This makes RVM work inside Vim. I have no idea why.
set shell=bash
" Prevent Vim from clobbering the scrollback buffer. See
" http://www.shallowsky.com/linux/noaltscreen.html
set t_ti= t_te=
" keep more context when scrolling off the end of a buffer
set scrolloff=3
" Store temporary files in a central spot
set backup
set backupdir=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp
set directory=~/.vim-tmp,~/.tmp,~/tmp,/var/tmp,/tmp
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
" display incomplete commands
set showcmd
" Enable highlighting for syntax
syntax on
" 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
" use emacs-style tab completion when selecting files, etc
set wildmode=longest,list
" make tab completion for files/buffers act like bash
set wildmenu
let mapleader=","
" Fix slow O inserts
:set timeout timeoutlen=1000 ttimeoutlen=100
" Normally, Vim messes with iskeyword when you open a shell file. This can
" leak out, polluting other file types even after a 'set ft=' change. This
" variable prevents the iskeyword change so it can't hurt anyone.
let g:sh_noisk=1
" Modelines (comments that set vim options on a per-file basis)
set modeline
set modelines=3
" Turn folding off for real, hopefully
set foldmethod=manual
set nofoldenable
let g:airline_left_sep = ''
let g:airline_left_alt_sep = ''
let g:airline_right_sep = ''
let g:airline_right_alt_sep = ''
let g:airline_fugitive_prefix = ' '
let g:airline_readonly_symbol = ''
let g:airline_linecolumn_prefix = ''
let g:airline_theme='badwolf'
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" CUSTOM AUTOCMDS
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
augroup vimrcEx
" Clear all autocmds in the group
autocmd!
autocmd FileType text setlocal textwidth=78
" Jump to last cursor position unless it's invalid or in an event handler
autocmd BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\ exe "normal g`\"" |
\ endif
"for ruby, autoindent with two spaces, always expand tabs
autocmd FileType ruby,haml,eruby,yaml,html,javascript,sass,cucumber set ai sw=2 sts=2 et
autocmd FileType python set sw=4 sts=4 et
autocmd! BufRead,BufNewFile *.sass setfiletype sass
autocmd BufRead *.mkd set ai formatoptions=tcroqn2 comments=n:>
autocmd BufRead *.markdown set ai formatoptions=tcroqn2 comments=n:>
" Indent p tags
" autocmd FileType html,eruby if g:html_indent_tags !~ '\\|p\>' | let g:html_indent_tags .= '\|p\|li\|dt\|dd' | endif
" Don't syntax highlight markdown because it's often wrong
autocmd! FileType mkd setlocal syn=off
" Leave the return key alone when in command line windows, since it's used
" to run commands there.
autocmd! CmdwinEnter * :unmap <cr>
autocmd! CmdwinLeave * :call MapCR()
augroup END
" Create the dirs required for a save if they don't exist.
function s:MkNonExDir(file, buf)
if empty(getbufvar(a:buf, '&buftype')) && a:file!~#'\v^\w+\:\/'
let dir=fnamemodify(a:file, ':h')
if !isdirectory(dir)
call mkdir(dir, 'p')
endif
endif
endfunction
augroup BWCCreateDir
autocmd!
autocmd BufWritePre * :call s:MkNonExDir(expand('<afile>'), +expand('<abuf>'))
augroup END
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" STATUS LINE
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
:set statusline=%<%f\ (%{&ft})\ %-4(%m%)%=%-19(%3l,%02c%03V%)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" MISC KEY MAPS
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
map <leader>y "*y
" Move around splits with <c-hjkl>
nnoremap <c-j> <c-w>j
nnoremap <c-k> <c-w>k
nnoremap <c-h> <c-w>h
nnoremap <c-l> <c-w>l
" Insert a hash rocket with <c-l>
imap <c-l> <space>=><space>
" Can't be bothered to understand ESC vs <c-c> in insert mode
imap <c-c> <esc>
nnoremap <leader><leader> <c-^>
" Close all other windows, open a vertical split, and open this file's test
" alternate in it.
nnoremap <leader>s :call FocusOnFile()<cr>
function! FocusOnFile()
tabnew %
normal! v
normal! l
call OpenTestAlternate()
normal! h
endfunction
" Reload in chrome
map <leader>l :w\|:silent !reload-chrome<cr>
" Align selected lines
vnoremap <leader>ib :!align<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" MULTIPURPOSE TAB KEY
" Indent if we're at the beginning of a line. Else, do completion.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! InsertTabWrapper()
let col = col('.') - 1
if !col || getline('.')[col - 1] !~ '\k'
return "\<tab>"
else
return "\<c-p>"
endif
endfunction
inoremap <tab> <c-r>=InsertTabWrapper()<cr>
inoremap <s-tab> <c-n>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" OPEN FILES IN DIRECTORY OF CURRENT FILE
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
cnoremap %% <C-R>=expand('%:h').'/'<cr>
map <leader>e :edit %%
map <leader>v :view %%
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" RENAME CURRENT FILE
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! RenameFile()
let old_name = expand('%')
let new_name = input('New file name: ', expand('%'), 'file')
if new_name != '' && new_name != old_name
exec ':saveas ' . new_name
exec ':silent !rm ' . old_name
redraw!
endif
endfunction
map <leader>n :call RenameFile()<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" PROMOTE VARIABLE TO RSPEC LET
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! PromoteToLet()
:normal! dd
" :exec '?^\s*it\>'
:normal! P
:.s/\(\w\+\) = \(.*\)$/let(:\1) { \2 }/
:normal ==
endfunction
:command! PromoteToLet :call PromoteToLet()
:map <leader>p :PromoteToLet<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" EXTRACT VARIABLE (SKETCHY)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! ExtractVariable()
let name = input("Variable name: ")
if name == ''
return
endif
" Enter visual mode (not sure why this is needed since we're already in
" visual mode anyway)
normal! gv
" Replace selected text with the variable name
exec "normal c" . name
" Define the variable on the line above
exec "normal! O" . name . " = "
" Paste the original selected text to be the variable value
normal! $p
endfunction
vnoremap <leader>rv :call ExtractVariable()<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" INLINE VARIABLE (SKETCHY)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! InlineVariable()
" Copy the variable under the cursor into the 'a' register
:let l:tmp_a = #a
:normal "ayiw
" Delete variable and equals sign
:normal 2daW
" Delete the expression into the 'b' register
:let l:tmp_b = #b
:normal "bd$
" Delete the remnants of the line
:normal dd
" Go to the end of the previous line so we can start our search for the
" usage of the variable to replace. Doing '0' instead of 'k$' doesn't
" work; I'm not sure why.
normal k$
" Find the next occurence of the variable
exec '/\<' . #a . '\>'
" Replace that occurence with the text we yanked
exec ':.s/\<' . #a . '\>/' . #b
:let #a = l:tmp_a
:let #b = l:tmp_b
endfunction
nnoremap <leader>ri :call InlineVariable()<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" MAPS TO JUMP TO SPECIFIC COMMAND-T TARGETS AND FILES
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
map <leader>gr :topleft :split config/routes.rb<cr>
function! ShowRoutes()
" Requires 'scratch' plugin
:topleft 100 :split __Routes__
" Make sure Vim doesn't write __Routes__ as a file
:set buftype=nofile
" Delete everything
:normal 1GdG
" Put routes output in buffer
:0r! zeus rake -s routes
" Size window to number of lines (1 plus rake output length)
:exec ":normal " . line("$") . "_ "
" Move cursor to bottom
:normal 1GG
" Delete empty trailing line
:normal dd
endfunction
map <leader>gR :call ShowRoutes()<cr>
map <leader>gv :CommandTFlush<cr>\|:CommandT app/views<cr>
map <leader>gc :CommandTFlush<cr>\|:CommandT app/controllers<cr>
map <leader>gm :CommandTFlush<cr>\|:CommandT app/models<cr>
map <leader>gh :CommandTFlush<cr>\|:CommandT app/helpers<cr>
map <leader>gl :CommandTFlush<cr>\|:CommandT lib<cr>
map <leader>gp :CommandTFlush<cr>\|:CommandT public<cr>
map <leader>gs :CommandTFlush<cr>\|:CommandT public/stylesheets<cr>
map <leader>gf :CommandTFlush<cr>\|:CommandT features<cr>
map <leader>gg :topleft 100 :split Gemfile<cr>
map <leader>gt :CommandTFlush<cr>\|:CommandTTag<cr>
map <leader>f :CommandTFlush<cr>\|:CommandT<cr>
map <leader>F :CommandTFlush<cr>\|:CommandT %%<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" SWITCH BETWEEN TEST AND PRODUCTION CODE
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! OpenTestAlternate()
let new_file = AlternateForCurrentFile()
exec ':e ' . new_file
endfunction
function! AlternateForCurrentFile()
let current_file = expand("%")
let new_file = current_file
let in_spec = match(current_file, '^spec/') != -1
let going_to_spec = !in_spec
let in_app = match(current_file, '\<controllers\>') != -1 || match(current_file, '\<models\>') != -1 || match(current_file, '\<views\>') != -1 || match(current_file, '\<helpers\>') != -1
if going_to_spec
if in_app
let new_file = substitute(new_file, '^app/', '', '')
end
let new_file = substitute(new_file, '\.e\?rb$', '_spec.rb', '')
let new_file = 'spec/' . new_file
else
let new_file = substitute(new_file, '_spec\.rb$', '.rb', '')
let new_file = substitute(new_file, '^spec/', '', '')
if in_app
let new_file = 'app/' . new_file
end
endif
return new_file
endfunction
nnoremap <leader>. :call OpenTestAlternate()<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" RUNNING TESTS
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! MapCR()
nnoremap <cr> :call RunTestFile()<cr>
endfunction
call MapCR()
nnoremap <leader>T :call RunNearestTest()<cr>
nnoremap <leader>a :call RunTests('')<cr>
nnoremap <leader>c :w\|:!script/features<cr>
nnoremap <leader>w :w\|:!script/features --profile wip<cr>
function! RunTestFile(...)
if a:0
let command_suffix = a:1
else
let command_suffix = ""
endif
" Run the tests for the previously-marked file.
let in_test_file = match(expand("%"), '\(.feature\|_spec.rb\)$') != -1
if in_test_file
call SetTestFile()
elseif !exists("t:grb_test_file")
return
end
call RunTests(t:grb_test_file . command_suffix)
endfunction
function! RunNearestTest()
let spec_line_number = line('.')
call RunTestFile(":" . spec_line_number)
endfunction
function! SetTestFile()
" Set the spec file that tests will be run for.
let t:grb_test_file=#%
endfunction
function! RunTests(filename)
" Write the file and run tests for the given filename
if expand("%") != ""
:w
end
if match(a:filename, '\.feature$') != -1
exec ":!script/features " . a:filename
else
" First choice: project-specific test script
if filereadable("script/test")
exec ":!script/test " . a:filename
" Fall back to the .test-commands pipe if available, assuming someone
" is reading the other side and running the commands
elseif filewritable(".test-commands")
let cmd = 'rspec --color --format progress --require "~/lib/vim_rspec_formatter" --format VimFormatter --out tmp/quickfix'
exec ":!echo " . cmd . " " . a:filename . " > .test-commands"
" Write an empty string to block until the command completes
sleep 100m " milliseconds
:!echo > .test-commands
redraw!
" Fall back to a blocking test run with Bundler
elseif filereadable("Gemfile")
exec ":!bundle exec rspec --color " . a:filename
" Fall back to a normal blocking test run
else
exec ":!rspec --color " . a:filename
end
end
endfunction
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" CtrlP Configuration
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:ctrlp_custom_ignore = '\v[\/]\.(git|hg|svn)$'
let g:ctrlp_user_command = 'find %s -type f'
let g:ctrlp_use_caching = 0
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Md5 COMMAND
" Show the MD5 of the current buffer
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
command! -range Md5 :echo system('echo '.shellescape(join(getline(<line1>, <line2>), '\n')) . '| md5')
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" OpenChangedFiles COMMAND
" Open a split for each dirty file in git
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! OpenChangedFiles()
only " Close all windows, unless they're modified
let status = system('git status -s | grep "^ \?\(M\|A\|UU\)" | sed "s/^.\{3\}//"')
let filenames = split(status, "\n")
exec "edit " . filenames[0]
for filename in filenames[1:]
exec "sp " . filename
endfor
endfunction
command! OpenChangedFiles :call OpenChangedFiles()
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" InsertTime COMMAND
" Insert the current time
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
command! InsertTime :normal a<c-r>=strftime('%F %H:%M:%S.0 %z')<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" FindConditionals COMMAND
" Start a search for conditional branches, both implicit and explicit
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
command! FindConditionals :normal /\<if\>\|\<unless\>\|\<and\>\|\<or\>\|||\|&&<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Diff tab management: open the current git diff in a tab
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
command! GdiffInTab tabedit %|vsplit|Gdiff
nnoremap <leader>d :GdiffInTab<cr>
nnoremap <leader>D :tabclose<cr>
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" RemoveFancyCharacters COMMAND
" Remove smart quotes, etc.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! RemoveFancyCharacters()
let typo = {}
let typo["“"] = '"'
let typo["”"] = '"'
let typo["‘"] = "'"
let typo["’"] = "'"
let typo["–"] = '--'
let typo["—"] = '---'
let typo["…"] = '...'
:exe ":%s/".join(keys(typo), '\|').'/\=typo[submatch(0)]/ge'
endfunction
command! RemoveFancyCharacters :call RemoveFancyCharacters()
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Selecta Mappings
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Run a given vim command on the results of fuzzy selecting from a given shell
" command. See usage below.
function! SelectaCommand(choice_command, selecta_args, vim_command)
try
silent let selection = system(a:choice_command . " | selecta " . a:selecta_args)
catch /Vim:Interrupt/
" Swallow the ^C so that the redraw below happens; otherwise there will be
" leftovers from selecta on the screen
redraw!
return
endtry
redraw!
exec a:vim_command . " " . selection
endfunction
" Find all files in all non-dot directories starting in the working directory.
" Fuzzy select one of those. Open the selected file with :e.
nnoremap <leader>f :call SelectaCommand("find * -type f", "", ":e")<cr>
function! SelectaIdentifier()
" Yank the word under the cursor into the z register
normal "zyiw
" Fuzzy match files in the current directory, starting with the word under
" the cursor
call SelectaCommand("find * -type f", "-s " . #z, ":e")
endfunction
nnoremap <c-g> :call SelectaIdentifier()<cr>
colorscheme jellybeans
highlight clear SignColumn
autocmd BufNewFile,BufRead *.mobile.erb let b:eruby_subtype='html'
autocmd BufNewFile,BufRead *.mobile.erb set filetype=eruby
autocmd BufNewFile,BufRead .pryrc set filetype=ruby
map <silent> <C-N> :silent noh<CR>
map <silent> <C-T> :NERDTree <CR>
map <silent> gb :Gblame<CR>
map <silent> gc :Gcommit<CR>
map <silent> gC :Gcommit -a<CR>
map <silent> gl :gitv<CR>
map <silent> gs :Gstatus<CR>
map <silent> ws :EraseBadWhitespace<CR>
"No arrow keys. :(
inoremap <Up> <NOP>
inoremap <Down> <NOP>
inoremap <Left> <NOP>
inoremap <Right> <NOP>
noremap <Up> <NOP>
noremap <Down> <NOP>
noremap <Left> <NOP>
noremap <Right> <NOP>
I added a comment, and then noticed that the very bottom of your vimrc file shows that I was right. The culprit is
:map <silent> ws :EraseBadWhitespace<CR>
According to :help map-modes, the :map command applies in Normal, Visual, Select, and Operator-pending modes. After you type c, vim enters Operator-pending mode, and then it waits to see if you just want w or if you plan to add an s. See also
:help 'timeout'

Is there any tip or trick to easily select the first word of (g)Vim's omni completion pop up?

For instance, if I write <?ph
The following words may pop up (and php is highlighted in the menu but not displayed in the code):
php
phrase
phrases
If I hit Tab or CTRL + N it just goes "Back at original."
If I press Shift + Tab or CTRL + P it goes to phrase.
While php is highlighted in the menu, If I press enter ph doesn't get completed.
I'm not sure if this is a normal behaviour in Vim or something wrong with my .vimrc:
" SHORTCUTS
nnoremap <F4> :set filetype=html<CR>
nnoremap <F5> :set filetype=php<CR>
nnoremap <F3> :TlistToggle<CR>
" press space to turn off highlighting and clear any message already displayed.
nnoremap <silent> <Space> :nohlsearch<Bar>:echo<CR>
" set buffers commands
nnoremap <silent> <M-F8> :BufExplorer<CR>
nnoremap <silent> <F8> :bn<CR>
nnoremap <silent> <S-F8> :bp<CR>
" open NERDTree with start directory: D:\wamp\www
nnoremap <F9> :NERDTree /home/alex/www<CR>
" open MRU
nnoremap <F10> :MRU<CR>
" open current file (silently)
nnoremap <silent> <F11> :let old_reg=#"<CR>:let #"=substitute(expand("%:p"), "/", "\\", "g")<CR>:silent!!cmd /cstart <C-R><C-R>"<CR><CR>:let #"=old_reg<CR>
" open current file in localhost (default browser)
nnoremap <F12> :! start "http://localhost" file:///"%:p""<CR>
" open Vim's default Explorer
nnoremap <silent> <F2> :Explore<CR>
nnoremap <C-F2> :%s/\.html/.php/g<CR>
"
set completeopt=menu,preview,longest
" REMAPPING
" map leader to ,
let mapleader = ","
" remap ` to '
nnoremap ' `
nnoremap ` '
" remap increment numbers
nnoremap <C-kPlus> <C-A>
" COMPRESSION
function Js_css_compress ()
let cwd = expand('<afile>:p:h')
let nam = expand('<afile>:t:r')
let ext = expand('<afile>:e')
if -1 == match(nam, "[\._]src$")
let minfname = nam.".min.".ext
else
let minfname = substitute(nam, "[\._]src$", "", "g").".".ext
endif
if ext == 'less'
if executable('lessc')
cal system( 'lessc '.cwd.'/'.nam.'.'.ext.' &')
endif
else
if filewritable(cwd.'/'.minfname)
if ext == 'js' && executable('closure-compiler')
cal system( 'closure-compiler --js '.cwd.'/'.nam.'.'.ext.' > '.cwd.'/'.minfname.' &')
elseif executable('yuicompressor')
cal system( 'yuicompressor '.cwd.'/'.nam.'.'.ext.' > '.cwd.'/'.minfname.' &')
endif
endif
endif
endfunction
autocmd FileWritePost,BufWritePost *.js :call Js_css_compress()
autocmd FileWritePost,BufWritePost *.css :call Js_css_compress()
autocmd FileWritePost,BufWritePost *.less :call Js_css_compress()
" GUI
" taglist right side
let Tlist_Use_Right_Window = 1
" hide tool bar
set guioptions-=T
"remove scroll bars
set guioptions+=LlRrb
set guioptions-=LlRrb
" set the initial size of window
set lines=46 columns=180
" set default font
set guifont=Monospace
" set guifont=Monospace\ 10
" show line number
set number
" set default theme
colorscheme ir_dark
" encoding
set encoding=utf-8
setglobal fileencoding=utf-8 bomb
set fileencodings=ucs-bom,utf-8,latin1
" SCSS syntax highlight
au BufRead,BufNewFile *.scss set filetype=scss
" LESS syntax highlight
syntax on
au BufNewFile,BufRead *.less set filetype=less
" Haml syntax highlight
"au! BufRead,BufNewFile *.haml
"setfiletype haml
" Sass syntax highlight
"au! BufRead,BufNewFile *.sass
"setfiletype sass
" set filetype indent
filetype indent on
" for snipMate to work
filetype plugin on
" show breaks
set showbreak=----->
" coding format
set tabstop=4
set shiftwidth=4
set linespace=1
" CONFIG
" keep the buffer around when left
set hidden
" enable matchit plugin
source $VIMRUNTIME/macros/matchit.vim
" folding
set foldmethod=marker
set foldmarker={,}
let g:FoldMethod = 0
map <leader>ff :call ToggleFold()<cr>
fun! ToggleFold()
if g:FoldMethod == 0
exe 'set foldmethod=indent'
let g:FoldMethod = 1
else
exe 'set foldmethod=marker'
let g:FoldMethod = 0
endif
endfun
" save and restore folds when a file is closed and re-opened
"au BufWrite ?* mkview
"au BufRead ?* silent loadview
" auto-open NERDTree everytime Vim is invoked
au VimEnter * NERDTree /home/alex/www
" set omnicomplete
autocmd FileType python set omnifunc=pythoncomplete#Complete
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd FileType html set omnifunc=htmlcomplete#CompleteTags
autocmd FileType css set omnifunc=csscomplete#CompleteCSS
autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
autocmd FileType c set omnifunc=ccomplete#Complete
" Improve completion popup menu
inoremap <expr> <Esc> pumvisible() ? "\<C-e>" : "\<Esc>"
inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<CR>"
inoremap <expr> <Down> pumvisible() ? "\<C-n>" : "\<Down>"
inoremap <expr> <Up> pumvisible() ? "\<C-p>" : "\<Up>"
inoremap <expr> <PageDown> pumvisible() ? "\<PageDown>\<C-p>\<C-n>" : "\<PageDown>"
inoremap <expr> <PageUp> pumvisible() ? "\<PageUp>\<C-p>\<C-n>" : "\<PageUp>"
" Remove trailing white-space once the file is saved
au BufWritePre * silent g/\s\+$/s///
" Use CTRL-S for saving, also in Insert mode
noremap <C-S> :update!<CR>
vnoremap <C-S> <C-C>:update!<CR>
inoremap <C-S> <C-O>:update!<CR>
" DEFAULT
set nocompatible
source $VIMRUNTIME/vimrc_example.vim
"source $VIMRUNTIME/mswin.vim
"behave mswin
" disable creation of swap files
set noswapfile
" no back ups wwhile editing
set nowritebackup
" disable creation of backups
set nobackup
" no file change pop up warning
autocmd FileChangedShell * echohl WarningMsg | echo "File changed shell." | echohl None
set diffexpr=MyDiff()
function MyDiff()
let opt = '-a --binary '
if &diffopt =~ 'icase' | let opt = opt . '-i ' | endif
if &diffopt =~ 'iwhite' | let opt = opt . '-b ' | endif
let arg1 = v:fname_in
if arg1 =~ ' ' | let arg1 = '"' . arg1 . '"' | endif
let arg2 = v:fname_new
if arg2 =~ ' ' | let arg2 = '"' . arg2 . '"' | endif
let arg3 = v:fname_out
if arg3 =~ ' ' | let arg3 = '"' . arg3 . '"' | endif
let eq = ''
if $VIMRUNTIME =~ ' '
if &sh =~ '\<cmd'
let cmd = '""' . $VIMRUNTIME . '\diff"'
let eq = '"'
else
let cmd = substitute($VIMRUNTIME, ' ', '" ', '') . '\diff"'
endif
else
let cmd = $VIMRUNTIME . '\diff'
endif
silent execute '!' . cmd . ' ' . opt . arg1 . ' ' . arg2 . ' > ' . arg3 . eq
endfunction
Is there a way to choose the first word immediately?
EDIT:
:map <c-y> says:
n <C-Y>A <Plug>ZenCodingAnchorizeSummary
n <C-Y>a <Plug>ZenCodingAnchorizeURL
n <C-Y>k <Plug>ZenCodingRemoveTag
n <C-Y>j <Plug>ZenCodingSplitJoinTagNormal
n <C-Y>/ <Plug>ZenCodingToggleComment
n <C-Y>i <Plug>ZenCodingImageSize
n <C-Y>N <Plug>ZenCodingPrev
n <C-Y>n <Plug>ZenCodingNext
v <C-Y>D <Plug>ZenCodingBalanceTagOutwardVisual
n <C-Y>D <Plug>ZenCodingBalanceTagOutwardNormal
v <C-Y>d <Plug>ZenCodingBalanceTagInwardVisual
n <C-Y>d <Plug>ZenCodingBalanceTagInwardNormal
n <C-Y>; <Plug>ZenCodingExpandWord
n <C-Y>, <Plug>ZenCodingExpandNormal
v <C-Y>, <Plug>ZenCodingExpandVisual
Use ctrl-y to select the currently highlighted option in the list. ctrl-n and p will go through the list next/previous, but y will select current.
In your .vimrc you have added "longest" to the completeopt option:
set completeopt=menu,preview,longest
This means that omni completion can only fill in the longest common substring of all possible matches. If you just use :set completeopt=menu,preview then vim should select the first match when using omni completion.

Turn off the highlight feature in the Limp

I am using the Limp in my VIM. But there is a problem, when the cursor move to a "(" or ")", it would highlight a block of code in this pair.I can not see the code clearly. Is there any way to turn off or delete this feature?
Best Regards,
I'm also using Limp but I have modified it somewhat to work better for my tastes.
Inside the main limp folder there is a vim subfolder, open the file limp.vim and at the end you can see several runtime commands, just comment out the one that loads the highlight.vim file:
"runtime ftplugin/lisp/limp/highlight.vim
I also like to disable the autoclose.vim plugin, I find it very annoying.
"runtime ftplugin/lisp/limp/autoclose.vim
Then, open the file mode.vim and around line number 58 you can see the function call to initialize the highlighting mode; comment it out:
"call LimpHighlight_start()
then around line number 68, under the function LimpMode_stop() you will also need to comment the call to stop the highlightning.
"call LimpHighlight_stop()
Of course, if you also disabled the autoclose.vim plugin you'll also have to comment the calls to start/stop it.
Annoying colors
If the colors that Limp sets up out of the box annoys you as they did with me, you can disable that and continue using your default colorscheme; around line number 30:
"set t_Co=256
"if !exists("g:colors_name")
"colorscheme desertEx
"endif
And change the highlight groups to match your colorscheme (use :high to quickly see a list of color combinations). For example, I use the "desertEx" colorscheme and changed this two lines to match it:
hi BracketsBlock ctermbg=235 guibg=grey22
hi StatusLine ctermbg=black ctermfg=160
Other options
I didn't like the set of options that Limp sets, especially the old Vi Lisp indentation. I also dislike the folding so I disabled that too. My current set of options look like this:
syntax on
setlocal nocompatible nocursorline
setlocal lisp syntax=lisp
setlocal ls=2 bs=2 et sw=2 ts=2 "tw=0
setlocal statusline=%<%f\ \(%{LimpBridge_connection_status()}\)\ %h%m%r%=%-14.(%l,%c%V%)\ %P
"setlocal iskeyword=&,*,+,45,/,48-57,:,<,=,>,#,A-Z,a-z,_
"setlocal cpoptions=-mp
"setlocal foldmethod=marker foldmarker=(,) foldminlines=1
setlocal foldcolumn=0
set lispwords+=defgeneric,block,catch,with-gensyms
"-----------
"Taken from the bundled lisp.vim file in VIM
"(/usr/share/vim/vim72/ftplugin/lisp.vim)
setl comments=:;
setl define=^\\s*(def\\k*
setl formatoptions-=t
setl iskeyword+=+,-,*,/,%,<,=,>,:,$,?,!,#-#,94
setl comments^=:;;;,:;;,sr:#\|,mb:\|,ex:\|#
setl formatoptions+=croql
"-----------
" This allows gf and :find to work. Fix path to your needs
setlocal suffixesadd=.lisp,.cl path+=/home/gajon/Lisp/**
Notice I disabled the tw=0, modified the statusline, disabled folding, copied the options that come bundled with Vim (they are a lot better), added some symbols to lispwords, and added a missing dot to suffixesadd (cl extension was missing a dot).
Disabling the transposing of sexps.
Limp binds they keys { and } to functions that transpose the current sexp with the previous/next sexp. But they don't work reliably and I think they are unnecessary when you can just as easily use dab and p at the proper place. Besides the default Vim {} bindings are quite useful to move to other top-level forms.
In file keys.vim:
"nmap <buffer> { <Plug>SexpMoveBack
"nmap <buffer> } <Plug>SexpMoveForward
Bug when connecting to a running REPL
There's a bug that prevents Limp from reconnecting to an already running REPL. In file bridge.vim inside the vim subfolder, around line number 13:
let cmd = s:Limp_location . "/bin/lisp.sh ".core_opt." -s ".styfile." -b ".name
A space was missing between ".core_opt." and -s.
Additional Goodies!
You should be able to figure out how to use these new mappings.
In file bridge.vim add the following lines after line number 265:
nnoremap <silent> <buffer> <Plug>EvalUndefine :call LimpBridge_send_to_lisp("(fmakunbound '".expand("<cword>").")")<CR>
nnoremap <silent> <buffer> <Plug>EvalAddWord :let &lispwords.=',' . expand("<cword>")<cr>
nnoremap <silent> <buffer> <Plug>DebugTrace :call LimpBridge_send_to_lisp("(trace ".expand("<cword>").")")<CR>
nnoremap <silent> <buffer> <Plug>DebugUnTrace :call LimpBridge_send_to_lisp("(untrace ".expand("<cword>").")")<CR>
nnoremap <silent> <buffer> <Plug>DebugInspectObject :call LimpBridge_inspect_expression()<CR>
nnoremap <silent> <buffer> <Plug>DebugInspectLast :call LimpBridge_send_to_lisp("(inspect *)")<CR>
nnoremap <silent> <buffer> <Plug>DebugDisassemble :call LimpBridge_send_to_lisp("(disassemble #'".expand("<cword>").")")<CR>
nnoremap <silent> <buffer> <Plug>DebugMacroExpand :call LimpBridge_macroexpand_current_form( "macroexpand" )<CR>
nnoremap <silent> <buffer> <Plug>DebugMacroExpand1 :call LimpBridge_macroexpand_current_form( "macroexpand-1" )<CR>
nnoremap <silent> <buffer> <Plug>ProfileSet :call LimpBridge_send_to_lisp("(sb-profile:profile ".expand("<cword>").")")<CR>
nnoremap <silent> <buffer> <Plug>ProfileUnSet :call LimpBridge_send_to_lisp("(sb-profile:unprofile ".expand("<cword>").")")<CR>
nnoremap <silent> <buffer> <Plug>ProfileShow :call LimpBridge_send_to_lisp("(sb-profile:profile)")<CR>
nnoremap <silent> <buffer> <Plug>ProfileUnSetAll :call LimpBridge_send_to_lisp("(sb-profile:unprofile)")<CR>
nnoremap <silent> <buffer> <Plug>ProfileReport :call LimpBridge_send_to_lisp("(sb-profile:report)")<CR>
nnoremap <silent> <buffer> <Plug>ProfileReset :call LimpBridge_send_to_lisp("(sb-profile:reset)")<CR>
And at the end add these two functions:
function! LimpBridge_inspect_expression()
let whatwhat = input("Inspect: ")
call LimpBridge_send_to_lisp( "(inspect " . whatwhat . ")" )
endfun
function! LimpBridge_macroexpand_current_form(command)
" save position
let pos = LimpBridge_get_pos()
" find & yank current s-exp
normal! [(
let sexp = LimpBridge_yank( "%" )
call LimpBridge_send_to_lisp( "(" . a:command . " '" . sexp . ")" )
call LimpBridge_goto_pos( pos )
endfunction
Then in file keys.vim add the following mappings:
" Undefine: Undefine a function or macro.
nmap <buffer> <LocalLeader>eu <Plug>EvalUndefine
" Add Word: Append word to 'lispwords' option
nmap <buffer> <LocalLeader>ea <Plug>EvalAddWord
" Trace: Set tracing for function.
" Untrace: Remove tracing for a function.
nmap <buffer> <LocalLeader>dt <Plug>DebugTrace
nmap <buffer> <LocalLeader>du <Plug>DebugUnTrace
" Inspect: Inspect object
" InspectPrev: Inspect last value evaled.
nmap <buffer> <LocalLeader>di <Plug>DebugInspectObject
nmap <buffer> <LocalLeader>dI <Plug>DebugInspectLast
" Disassemble:
nmap <buffer> <LocalLeader>dd <Plug>DebugDisassemble
" Macroexpand:
" Macroexpand1:
nmap <buffer> <LocalLeader>ma <Plug>DebugMacroExpand
nmap <buffer> <LocalLeader>m1 <Plug>DebugMacroExpand1
" Profile: Set profiling.
" Unprofile: Remove profiling.
nmap <buffer> <LocalLeader>pr <Plug>ProfileSet
nmap <buffer> <LocalLeader>pu <Plug>ProfileUnSet
" Show Profiling: Show profiling.
" Unprofile All: Remove all profiling.
nmap <buffer> <LocalLeader>pp <Plug>ProfileShow
nmap <buffer> <LocalLeader>pa <Plug>ProfileUnSetAll
" Profile Report: Show report.
" Profile Reset: Reset profile data.
nmap <buffer> <LocalLeader>ps <Plug>ProfileReport
nmap <buffer> <LocalLeader>p- <Plug>ProfileReset
" Sexp Close Open Parenthesis:
nmap <buffer> <LocalLeader>cp <Plug>SexpCloseParenthesis
imap <buffer> <C-X>0 <C-O><LocalLeader>cp
Then in file sexp.vim add this mapping:
" Sexp Close Open Parenthesis:
nnoremap <silent> <buffer> <Plug>SexpCloseParenthesis :call SlimvCloseForm()<CR>
and these two functions:
"-------------------------------------------------------------------
" Close open parenthesis
" Taken from the Slimv plugin by Tamas Kovacs. Released in the
" public domain by the original author.
"-------------------------------------------------------------------
" Count the opening and closing parens or brackets to determine if they match
function! s:GetParenCount( lines )
let paren = 0
let inside_string = 0
let i = 0
while i < len( a:lines )
let inside_comment = 0
let j = 0
while j < len( a:lines[i] )
if inside_string
" We are inside a string, skip parens, wait for closing '"'
if a:lines[i][j] == '"'
let inside_string = 0
endif
elseif inside_comment
" We are inside a comment, skip parens, wait for end of line
else
" We are outside of strings and comments, now we shall count parens
if a:lines[i][j] == '"'
let inside_string = 1
endif
if a:lines[i][j] == ';'
let inside_comment = 1
endif
if a:lines[i][j] == '(' || a:lines[i][j] == '['
let paren = paren + 1
endif
if a:lines[i][j] == ')' || a:lines[i][j] == ']'
let paren = paren - 1
if paren < 0
" Oops, too many closing parens in the middle
return paren
endif
endif
endif
let j = j + 1
endwhile
let i = i + 1
endwhile
return paren
endfunction
" Close current top level form by adding the missing parens
function! SlimvCloseForm()
let l2 = line( '.' )
normal 99[(
let l1 = line( '.' )
let form = []
let l = l1
while l <= l2
call add( form, getline( l ) )
let l = l + 1
endwhile
let paren = s:GetParenCount( form )
if paren > 0
" Add missing parens
let lastline = getline( l2 )
while paren > 0
let lastline = lastline . ')'
let paren = paren - 1
endwhile
call setline( l2, lastline )
endif
normal %
endfunction
Hope this helps you better use Limp.

Resources