In my .vimrc, I have:
:au BufWinEnter * let w:m1=matchadd('Search', '\%>80v.\+', -1)
to highlight lines that stray over the 80 character limit. How can I set it so that this is toggled on/off by pressing a function key?
Use mappings.
To activate highlight:
:nnoremap <leader>1 :match Search '\%>80v.\+'<CR>
To deactivate it:
:nnoremap <leader>2 :match none<CR>
UPDATE to use same key/key combination to toggle highlight:
let s:activatedh = 0
function! ToggleH()
if s:activatedh == 0
let s:activatedh = 1
match Search '\%>80v.\+'
else
let s:activatedh = 0
match none
endif
endfunction
nnoremap <leader>1 :call ToggleH()<CR>
Related
I've set up some options in my .vimrc so that it toggles to relative line numbering when in visual modes and switches back to absolute when hitting escape. The problem is every time I switch modes, it brings the cursor back to the first column. I am trying to stop this.
My original code is as follows and is inspired by this post.
So my code is
autocmd InsertEnter * :set norelativenumber
autocmd InsertLeave * :set relativenumber
function! SetLineNumbersVisual()
set relativenumber
return
endfunction
function! ResetLineNumbering()
set norelativenumber
return
endfunction
map <Esc> :call ResetLineNumbering()<CR>
vnoremap <silent> <expr> <SID>SetLineNumbersVisual SetLineNumbersVisual()
nnoremap <silent> <script> v v<SID>SetLineNumbersVisual
nnoremap <silent> <script> V V<SID>SetLineNumbersVisual
nnoremap <silent> <script> <C-v> <C-v><SID>SetLineNumbersVisual
augroup LineNumberSwap
autocmd!
autocmd InsertEnter * call ResetLineNumbering()
autocmd InsertLeave * call ResetLineNumbering()
autocmd CursorHold * call ResetLineNumbering()
augroup END
So that code swaps to relative when in any visual mode and then upon exiting brings it back to absolute. What is also does it constantly move the cursor back to the first column.
To fix this I tried determining the cursor position before setting the mode and then forcing the cursor to move back, but does this doesn't seem to work.
function! SetLineNumbersVisual()
let l:cur_pos = getpos(".")
set relativenumber
call cursor(l:cur_pos[1],l:cur_pos[2])
return
endfunction
function! ResetLineNumbering()
let l:cur_pos = getpos(".")
set norelativenumber
call cursor(l:cur_pos[1],l:cur_pos[2])
return
endfunction
Isn't fixing the problem though.
If you don't specify a return expression, 0 is returned, which evaluates to "go to the first character" motion.
You want to return an empty string:
function! SetLineNumbersVisual()
set relativenumber
return ''
endfunction
Is there a way to have the search highlight text in vim under the cursor have a different color compared to the search text not under the cursor?
my .vimrc has this codes:
function! HiInterestingWord(n) " {{{2
" Save our location.
normal! mz
" Yank the current word into the z register.
normal! "zyiw
" Calculate an arbitrary match ID. Hopefully nothing else is using it.
let mid = 77750 + a:n
" Clear existing matches, but don't worry if they don't exist.
"silent! call matchdelete(mid)
try
call matchdelete(mid)
catch 'E803'
" Construct a literal pattern that has to match at boundaries.
let pat = '\V\<' . escape(#z, '\') . '\>'
" Actually match the words.
call matchadd("InterestingWord" . a:n, pat, 1, mid)
endtry
" Move back to our original location.
normal! `z
endfunction
"clear all highlighting
function! ClearAllHi()
for i in range(1,6)
let mid = 77750 + i
silent! call matchdelete(mid)
endfor
endfunction
nnoremap <silent> <leader>0 :call ClearAllHi()<cr>
nnoremap <silent> <leader>1 :call HiInterestingWord(1)<cr>
nnoremap <silent> <leader>2 :call HiInterestingWord(2)<cr>
nnoremap <silent> <leader>3 :call HiInterestingWord(3)<cr>
nnoremap <silent> <leader>4 :call HiInterestingWord(4)<cr>
nnoremap <silent> <leader>5 :call HiInterestingWord(5)<cr>
nnoremap <silent> <leader>6 :call HiInterestingWord(6)<cr>
hi def InterestingWord1 guifg=#000000 ctermfg=16 guibg=#ffa724 ctermbg=214
hi def InterestingWord2 guifg=#000000 ctermfg=16 guibg=#aeee00 ctermbg=154
hi def InterestingWord3 guifg=#000000 ctermfg=16 guibg=#8cffba ctermbg=121
hi def InterestingWord4 guifg=#000000 ctermfg=16 guibg=#b88853 ctermbg=137
hi def InterestingWord5 guifg=#000000 ctermfg=16 guibg=#ff9eb8 ctermbg=211
hi def InterestingWord6 guifg=#000000 ctermfg=16 guibg=#ff2c4b ctermbg=195
"}}}
This allows you to press <leader> + 1-6 to high light word under cursor in different colors; pressing it twice to clear the highlighting. (You can change the color in hi def...) commands. And <leader>+0 clear all highlights.
You can just put the codes in your vimrc to try.
It works like this:
People have used solution based on Damian Conway's talk
" Damian Conway's Die Blinkënmatchen: highlight matches
nnoremap <silent> n n:call HLNext(0.1)<cr>
nnoremap <silent> N N:call HLNext(0.1)<cr>
function! HLNext (blinktime)
let target_pat = '\c\%#'.#/
let ring = matchadd('ErrorMsg', target_pat, 101)
redraw
exec 'sleep ' . float2nr(a:blinktime * 1000) . 'm'
call matchdelete(ring)
redraw
endfunction
But personally, I prefer a simple one, though this highlight whole line
"cursorline and it's highlighting
set cursorline
hi CursorLine cterm=NONE ctermbg=NONE ctermfg=green
I have follwing in my .vimrc to hightlight all words that matches the one on current cursor
autocmd CursorMoved * silent! exe printf('match Search /\<%s\>/', expand('<cword>'))
But sometimes it is a little annoying, so I'd like to map a key to turn on or off it, e.g. <F10>
How can I do this?
Clear the autocommand and remove highlight:
nmap <f8> :autocmd! CursorMoved<cr> :call clearmatches()<cr>
and to turn it back on using a different key:
nmap <f9> :autocmd CursorMoved * silent! exe printf('match Search /\<%s\>/', expand('<cword>'))<cr>
Put the following in your .vimrc:
let g:toggleHighlight = 0
function! ToggleHighlight(...)
if a:0 == 1 "toggle behaviour
let g:toggleHighlight = 1 - g:toggleHighlight
endif
if g:toggleHighlight == 0 "normal action, do the hi
silent! exe printf('match Search /\<%s\>/', expand('<cword>'))
else
"do whatever you need to clear the matches
"or nothing at all, since you are not printing the matches
endif
endfunction
autocmd CursorMoved * call ToggleHighlight()
map <F8> :call ToggleHighlight(1)<CR>
The idea is, if you call the function with an argument it changes the behavior to print/no print.
The autocommand just uses the last setting because the function there is called without an argument.
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.
Is there any way to make Vim (or gVim, or both) highlight the right margin of the current buffer?
I have just begun to work with Vim for a while, and find it annoying not to have the right margin visible (say, at column 80).
Vim 7.3 introduced colorcolumn.
:set colorcolumn=80
It may be easier for you to remember the short form.
:set cc=80
There is no simple way to visualize a vertical edge for the
textwidth-margin in Vim 7.2 or earlier; starting with version 7.3,
there is dedicated colorcolumn option. However, one can highlight
all characters beyond the 80-column limit using the :match command:
:match ErrorMsg /\%>80v.\+/
All we need to make it a general solution, is to build the match
pattern on the fly to substitute the correct value of the textwidth
option:
:autocmd BufWinEnter * call matchadd('ErrorMsg', '\%>'.&l:textwidth.'v.\+', -1)
I've written a vimscript function in my .vimrc to toggle colorcolumn when I press ,8 (comma followed by 8, where comma is the defined leader for user-defined commands, and eight is my mnemonic key for 'show a margin at the 80th column):
" toggle colored right border after 80 chars
set colorcolumn=81
let s:color_column_old = 0
function! s:ToggleColorColumn()
if s:color_column_old == 0
let s:color_column_old = &colorcolumn
windo let &colorcolumn = 0
else
windo let &colorcolumn=s:color_column_old
let s:color_column_old = 0
endif
endfunction
nnoremap <Leader>8 :call <SID>ToggleColorColumn()<cr>
I've rewritten the answer of Jonathan Hartley for the older Vim versions like 7.2 as there is no colorcolumn in older Vims.
highlight OverLength ctermbg=red ctermfg=white guibg=#592929
let s:OverLengthToggleVariable=0
function! ToggleOverLength()
if s:OverLengthToggleVariable == 0
match OverLength /\%81v.\+/
let s:OverLengthToggleVariable=1
else
match OverLength //
let s:OverLengthToggleVariable=0
endif
endfunction
" I like <leader>h since highlight starts with h.
nnoremap <leader>h :call ToggleOverLength()<cr>