I have the following code inside my vimrc
hi CurrentWordUL cterm=underline gui=underline
hi Search cterm=underline ctermfg=124 gui=underline guifg=#af0000
augroup MyHighlighter
autocmd!
" autocmd User IncSearchEnter MatchHighlighter 0
" autocmd User IncSearchExecute MatchHighlighter 1
set updatetime=700
autocmd CursorHold * if (get(g:, 'matchhl', 1) && (&ft !~ join(g:ft_blacklist, '\|')))
\ | silent! exe printf('match CurrentWordUL /\<%s\>/', expand('<cword>'))
\ | endif
autocmd CursorMoved * if (get(g:, 'matchhl', 1) && (&ft !~ join(g:ft_blacklist, '\|')))
\ | silent! exe printf('match none')
\ | endif
augroup END
nnoremap <silent> <f4> :MatchHighlighter<CR>
command! -nargs=? MatchHighlighter
\ call ToggleSetMatchHL(
\ empty(<q-args>) ? !get(g:, 'matchhl', 1) : expand(<q-args>))
function! ToggleSetMatchHL(arg) abort
match none | diffupdate | syntax sync fromstart
let g:matchhl = a:arg
endfunction
The purpose of this is to highlight (underline) matching word under the cursor.
The issue I have is when I'm searching with /, ?, *, # etc. The matching highlight overwrite the search highlight.
Is there anyway I can know "end of search" (I don't know the definition of "end of search" but maybe someone can suggest something) or "nohlsearch" was called?
Thanks in advance.
If you switch from :match to :call matchadd(...), you can specify a {priority}. A negative one will put the highlighting below the search highlighting (which has prio 0; default is 10).
There's no event for "end of search". You could override all search-related commands (/, ?, *, etc); that would detect a start of search. For / and ?, you could define a cmap <CR> with a check of getcmdtype() =~# '[/?]' to detect the conclusion of a search. I wouldn't recommend this approach; the mappings may interfere with other plugins.
Instead of using :match (which is window-local, so the highlighting also behaves differently than the built-in search highlighting), you could automatically adapt the current search pattern (register /) instead. My SearchHighlighting plugin chooses this approach with its :SearchAutoHighlighting command. (The plugin page has links to many alternative plugins you may want to check out; I would prefer a well-maintained plugin over a custom code snippet in my ~/.vimrc.)
I have these in my vimrc:
if has("autocmd")
augroup Misc
" Jump to the last known position when reopening a file
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
augroup FTOptions
autocmd!
autocmd FileType cpp,java setlocal commentstring=//\ %s
autocmd FileType markdown setlocal textwidth=78 formatprg=par\ -w78
augroup END
In markdown files I'd like to do the formatting using par. It works well, but I get a warning if "par" is not installed on the system. I'm wondering if there's a way to check and only set "formatprg=par\ -78" when par is installed, otherwise use VIM's default formatting.
I would be grateful for any suggestion.
if executable('par')
" stuff
endif
I'm writing a small snippet for quickfix buffers. I need to add an autocmd for quickfix buffers for BufDelete event.
I have following in ~/.vim/ftplugin/qf.vim
augroup quickr_preview
autocmd!
autocmd BufDelete <buffer> echom "Hey"
augroup END
The autocmd is getting executed before the quickfix buffer is loaded. So the BufDelete autocmd gets set for the calling buffer and not the quickfix buffer.
I've also tried putting autocmd FileType qf autocmd BufDelete <buffer> echom "Hey" directly in my ~/.vimrc, but that has same effect.
How to go about this?
For now I'm going with following.
function! QuickFixBufDelete()
if &buftype == 'quickfix'
autocmd BufDelete <buffer> echom "Hey"
endif
endfunction
autocmd BufCreate * call QuickFixBufDelete()
This is not good as the autocmd gets invoked for all filetypes and then I check for the filetype in my function.
The current answer is no longer working for me. I am now trying the BufReadPost auto command, and it seems to be playing nicely ...
augroup quickr_preview_auto_cmds
autocmd!
autocmd BufReadPost quickfix
\ if !exists('b:quickr_preview_auto_cmds')
\ | exe 'autocmd BufDelete <buffer> pclose! | sign unplace 26'
\ | let b:quickr_preview_auto_cmds = 1
\ | endif
augroup END
This matches what is described in the vim help for qiuckfix-window ...
When the quickfix window has been filled, two autocommand events are
triggered. First the 'filetype' option is set to "qf", which triggers the
FileType event. Then the BufReadPost event is triggered, using "quickfix" for
the buffer name. This can be used to perform some action on the listed
errors.
I am experiencing some very painful lag when accessing directories/files over UNC paths using gVim 7.3 on Windows Vista.
It is slow reading/writing files, as well as tab completiong of directory/file names when opening new buffers. I don't notice this lag when using WordPad though.
Things I've tried:
Cream (apparently they had a fix for directory naming schemes)
Mapping the network drive to z: or something else
Various settings
set ffs=dos
set complete=.,w,b,u,t
set noshellslash
I've tried cygwin, but the same noticeable lag appears there as well. I already have all swap/backup files turned off. Any help greatly appreciated... I've dumped my vimrc for reference
if v:progname =~? "evim"
finish
endif
set nocompatible
:runtime! ftplugin/man.vim
set backspace=indent,eol,start
colorscheme torte " murphy
syn on
set ffs=unix,dos
" portable friendly
set nobackup
set nowritebackup
set noswapfile
set viminfo=
" gui options (http://steveno.wordpress.com/2007/10/08/vim-for-windows/)
set guioptions-=T " No toolbar
set gfn=Consolas:h9:cANSI
set history=50
set ruler
set showcmd
set incsearch
set number
set tabstop=4
set softtabstop=4
set shiftwidth=4
set wrap
set wildmode=longest,list,full " Complete longest string, list alternatives
" then completed next full match, cycling back
function! ToggleHLSearch()
if &hls
set nohls
else
set hls
endif
endfunction
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>
nmap <silent> <C-n> <Esc>:call ToggleHLSearch()<CR>
nmap ,s :source ~/.vimrc<Return>
" change current directory to that of open buffer
nmap ,c :cd %:p:h<Return>
nmap <c-h> <c-w>h<c-w><bar>
nmap <c-l> <c-w>l<c-w><bar>
map <C-J> <C-W>j<C-W>_
map <C-K> <C-W>k<C-W>_
map Q gq
" Commenting blocks of text
" ,< <!-- --> html style comments
map ,< :s/^\(.*\)$/<!-- \1 -->/<CR><Esc>:nohlsearch<CR>
" ,/ // comments
map ,/ :s/^/\/\//<CR>
" ,# # comments
map ,# :s/^/#/<CR>
" uncommenting all of the above
"map ,- :s/^\(\/\/|<!-- |#\)\(.*\)\(-->\)*/\1/<CR>
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
if has("autocmd")
"&& !exists("autocommands_loaded")
let autocommands_loaded = 1
filetype plugin indent on
augroup vimrcEx
au!
" Remove ALL autocommands for the current group.
autocmd!
autocmd FileType text setlocal textwidth=78
autocmd BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\ exe "normal g`\"" |
\ endif
au BufRead *.html set filetype=html4
augroup END
" allow editing Word Docs sanely
autocmd BufReadPre *.doc set ro
autocmd BufReadPre *.doc set hlsearch!
autocmd BufReadPost *.doc %!antiword "%"
" uncomment the following to remember the view of the file edited between
" sessions
" au BufWinLeave * mkview
" au BufWinEnter * silent loadview
" run file with PHP CLI (CTRL-M)
autocmd FileType php noremap <C-M> :w!<CR>:!/usr/bin/php %<CR>
" parser check (CTRL-L)
autocmd FileType php noremap <C-L> :!/usr/bin/php -l %<CR>
" highlight current line only for current buffer
"autocmd BufLeave * setlocal nocursorline
"autocmd BufEnter * setlocal cursorline
au BufRead,BufNewFile *.tea set filetype=tea
"au! Syntax newlang source $VIM/newlanguage.vim
else
set autoindent
endif
the same thing was driving me insane, but there is a fix I just found.
I really do not know why yet, but the problem goes away when you disable plugin/matchparen.vim plugin (changing vim extension would do the trick).
I will definitely look into it as I use parentheses matching a lot.
See
:he swap-file
You can disable swapfiles with :se noswapfile (caution!) or use the `directory` setting to keep the swapfile on a local disk.
Starting vim with the -n option also disables swapfiles; you might want to combine that with -R for readonly mode
Another solution I found is that mounting a UNC path as a local drive letter and let Vim use the drive-letter based paths only.
e.g., \\some-server\path\to\workdir => Z:\path\to\workdir
This eliminates the lag completely unless you have connection problems.
I am getting 'trailing whitespace' errors trying to commit some files in Git.
I want to remove these trailing whitespace characters automatically right before I save Python files.
Can you configure Vim to do this? If so, how?
I found the answer here.
Adding the following to my .vimrc file did the trick:
autocmd BufWritePre *.py :%s/\s\+$//e
The e flag at the end means that the command doesn't issue an error message if the search pattern fails. See :h :s_flags for more.
Compilation of above plus saving cursor position:
function! <SID>StripTrailingWhitespaces()
if !&binary && &filetype != 'diff'
let l:save = winsaveview()
keeppatterns %s/\s\+$//e
call winrestview(l:save)
endif
endfun
autocmd FileType c,cpp,java,php,ruby,python autocmd BufWritePre <buffer> :call <SID>StripTrailingWhitespaces()
If you want to apply this on save to any file, leave out the second autocmd and use a wildcard *:
autocmd BufWritePre,FileWritePre,FileAppendPre,FilterWritePre *
\ :call <SID>StripTrailingWhitespaces()
I also usually have a :
match Todo /\s\+$/
in my .vimrc file, so that end of line whitespace are hilighted.
Todo being a syntax hilighting group-name that is used for hilighting keywords like TODO, FIXME or XXX. It has an annoyingly ugly yellowish background color, and I find it's the best to hilight things you don't want in your code :-)
I both highlight existing trailing whitespace and also strip trailing whitespace.
I configure my editor (vim) to show white space at the end, e.g.
with this at the bottom of my .vimrc:
highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\#<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()
and I 'auto-strip' it from files when saving them, in my case *.rb for ruby files, again in my ~/.vimrc
function! TrimWhiteSpace()
%s/\s\+$//e
endfunction
autocmd BufWritePre *.rb :call TrimWhiteSpace()
Here's a way to filter by more than one FileType.
autocmd FileType c,cpp,python,ruby,java autocmd BufWritePre <buffer> :%s/\s\+$//e
I saw this solution in a comment at
VIM Wikia - Remove unwanted spaces
I really liked it. Adds a . on the unwanted white spaces.
Put this in your .vimrc
" Removes trailing spaces
function TrimWhiteSpace()
%s/\s*$//
''
endfunction
set list listchars=trail:.,extends:>
autocmd FileWritePre * call TrimWhiteSpace()
autocmd FileAppendPre * call TrimWhiteSpace()
autocmd FilterWritePre * call TrimWhiteSpace()
autocmd BufWritePre * call TrimWhiteSpace()
Copied and pasted from http://blog.kamil.dworakowski.name/2009/09/unobtrusive-highlighting-of-trailing.html (the link no longer works, but the bit you need is below)
"This has the advantage of not highlighting each space you type at the end of the line, only when you open a file or leave insert mode. Very neat."
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\#<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
This is how I'm doing it. I can't remember where I stole it from tbh.
autocmd BufWritePre * :call <SID>StripWhite()
fun! <SID>StripWhite()
%s/[ \t]\+$//ge
%s!^\( \+\)\t!\=StrRepeat("\t", 1 + strlen(submatch(1)) / 8)!ge
endfun
A solution which simply strips trailing whitespace from the file is not acceptable in all circumstances. It will work in a project which has had this policy from the start, and so there are no such whitespace that you did not just add yourself in your upcoming commit.
Suppose you wish merely not to add new instances of trailing whitespace, without affecting existing whitespace in lines that you didn't edit, in order to keep your commit free of changes which are irrelevant to your work.
In that case, with git, you can can use a script like this:
#!/bin/sh
set -e # bail on errors
git stash save commit-cleanup
git stash show -p | sed '/^\+/s/ *$//' | git apply
git stash drop
That is to say, we stash the changes, and then filter all the + lines in the diff to remove their trailing whitespace as we re-apply the change to the working directory. If this command pipe is successful, we drop the stash.
The other approaches here somehow didn't work for me in MacVim when used in the .vimrc file. So here's one that does and highlights trailing spaces:
set encoding=utf-8
set listchars=trail:ยท
set list
For people who want to run it for specific file types (FileTypes are not always reliable):
autocmd BufWritePre *.c,*.cpp,*.cc,*.h,*.hpp,*.py,*.m,*.mm :%s/\s\+$//e
Or with vim7:
autocmd BufWritePre *.{c,cpp,cc,h,hpp,py,m,mm} :%s/\s\+$//e
If you trim whitespace, you should only do it on files that are already clean. "When in Rome...". This is good etiquette when working on codebases where spurious changes are unwelcome.
This function detects trailing whitespace and turns on trimming only if it was already clean.
The credit for this idea goes to a gem of a comment here: https://github.com/atom/whitespace/issues/10 (longest bug ticket comment stream ever)
autocmd BufNewFile,BufRead *.test call KarlDetectWhitespace()
fun! KarlDetectWhitespace()
python << endpython
import vim
nr_unclean = 0
for line in vim.current.buffer:
if line.rstrip() != line:
nr_unclean += 1
print "Unclean Lines: %d" % nr_unclean
print "Name: %s" % vim.current.buffer.name
cmd = "autocmd BufWritePre <buffer> call KarlStripTrailingWhitespace()"
if nr_unclean == 0:
print "Enabling Whitespace Trimming on Save"
vim.command(cmd)
else:
print "Whitespace Trimming Disabled"
endpython
endfun
fun! KarlStripTrailingWhitespace()
let l = line(".")
let c = col(".")
%s/\s\+$//e
call cursor(l, c)
endfun
autocmd BufWritePre *.py execute 'norm m`' | %s/\s\+$//e | norm g``
This will keep the cursor in the same position as it was just before saving
autocmd BufWritePre * :%s/\s\+$//<CR>:let #/=''<CR>