I am trying to write my first vim function (toggling hidden chars).
This is what I have so far
set nolist
set listchars=space:_,tab:▸\ ,eol:¬
nnoremap <leader>c :call showHiddenChars()<cr> "<---Calling function here
let g:showhiddenChars_is_visible = 0
function! showHiddenChars()
if g:showhiddenChars_is_visible
set nolist
let g:showhiddenChars_is_visible = 0
else
set list
let g:showhiddenChars_is_visible = 1
endif
endfunction
However when I run it I get the error invalid function showHiddenChars
Any suggestions. This is my first vim function.
User function names must begin with an uppercase letter (unless they are script functions with the s: prefix, or autoload functions using the foo#bar() syntax).
Change your function name from showHiddenChars to ShowHiddenChars and it should work as expected.
Related
I am looking for a way to map NERDTree-<CR> on some condition.
If current window is empty, NERDTree-<CR> is mapped to NERDTree-o. If it is not, mapped to NERDTree-t.
I am a beginner of vimscript, so it is hard to find how to do it.
I tried to make a function like below and the function to be called on 'NERDTreeCustomArgsOpen', but couldn't make it.
" Couldn't make 'IsBufferModifiable' function
" and mapping 'MyNERDTree_CR' to 'NERDTreeCustomOpenArgs'
function! IsBufferModifiable(numBuffer)
function! IsBufferEmpty(numBuffer)
return bufname(a:numBuffer) == ''
endfunction
function! IsModifiableBufferEmpty()
let emptyModifiableBuffers = filter(range(1, bufnr('$')), 'IsBufferModifiable(v:val) && IsBufferEmpty(v:val)')
if len(emptyModifiableBuffers) == 0
return 1
else
return 0
endfunction
function! MyNERDTree_CR()
if IsModifiableBufferEmpty()
call feedkeys('o')
else
call feedkeys('t')
endfunction
" Not sure it works or not
let NERDTreeCustomOpenArgs = {'file':{'where':'MyNERDTree_CR', 'reuse':'all', 'keepopen':1, 'stay':1}}
Is there any way to make them work?
Checking if a given buffer is modifiable is usually done by checking the value of the buffer-local :help 'modifiable' option:
function! IsBufferModifiable(numBuffer)
return getbufvar(a:numBuffer, '&modifiable')
endfunction
See :help getbufvar().
Let's say I have some combination of:
" one if not both is usually on
set number " could be on or off
set relativenumber " could be on or off
Is there a way to toggle these on/off without losing information (not knowing what is set -- i.e., I would like to make a simple keyboard shortcut to toggle the visibility of the current line-number selection)? For example if I have only rnu set and I do:
:set number!
It really doesn't help me at all, since I'll still have rnu set and there will still be a line-number column on the left. If so, how could this be done?
give this a try:
currently, I am mapping it to <F7> you can change the mapping if you like
I am using the global variable, you can change the scope if it is required
This function will disable all line-number displays and restore to the old line number settings.
function! MagicNumberToggle() abort
if &nu + &rnu == 0
let &nu = g:old_nu
let &rnu = g:old_rnu
else
let g:old_nu = &nu
let g:old_rnu = &rnu
let &nu = 0
let &rnu =0
endif
endfunction
nnoremap <F7> :call MagicNumberToggle()<cr>
The one liner solution
:nnoremap <silent> <C-n> :let [&nu, &rnu] = [!&rnu, &nu+&rnu==1]<cr>
To understand what happens try:
:echo [&nu, !&rnu]
&nu ............. gets the value of number
!&rnu ........... the oposite value of relative number
For more :h nu
How can I reassign the value of a list in vim?
g:my_list = [1,2,3,4]
function! My_func(num)
set g:my_list[num] = 20
endfunction
:call My_func(2)
E518: Unknown option: g:my_list[num] =
You need to use let for variables, set is for options.
Additionally you need to prefix function arguments with a:
let g:my_list = [1,2,3,4]
function! My_func(num)
let g:my_list[a:num] = 20
endfunction
:call My_func(2)
See:
:help let in vim help
Vimscript variable scoping in http://www.ibm.com/developerworks/library/l-vim-script-1/index.html.
I edit a large C, C++, or Java file, say, about 15000 lines, with pretty long function definitions, say, about 400 lines. When the cursor is in middle of a function definition, it would be cool to see the function name in Vim status line.
When we set :set ls=2 in Vim, we can get the file path (relative to the current directory), line number, etc. It would be really cool if we could see the function name too. Any ideas how to get it?
Currently I use [[ to go to start of the function and Ctrl-O to get back to the line I'm editing.
To show current function name in C programs add following in your vimrc:
fun! ShowFuncName()
let lnum = line(".")
let col = col(".")
echohl ModeMsg
echo getline(search("^[^ \t#/]\\{2}.*[^:]\s*$", 'bW'))
echohl None
call search("\\%" . lnum . "l" . "\\%" . col . "c")
endfun
map f :call ShowFuncName() <CR>
Or if you need the "f" key, just map the function to whatever you like.
You can use ctags.vim for this, it will show the current function name in the title or status bar.
SOURCE: https://superuser.com/questions/279651/how-can-i-make-vim-show-the-current-class-and-method-im-editing
Based on #manav m-n's answer
The 'n' flag in search() won't move the cursor, so a shorter version of this with the same functionality would be:
fun! ShowFuncName()
echohl ModeMsg
echo getline(search("^[^ \t#/]\\{2}.*[^:]\s*$", 'bWn'))
echohl None
endfun
map f :call ShowFuncName() <CR>
Reference: run :help search()
Having investigated this and the accepted solution, I believe the simplest solution is:
Install Universal Ctags https://ctags.io/
Install Tagbar https://github.com/preservim/tagbar
call tagbar#currenttag() when setting your statusline, e.g. in .vimrc:
:set statusline=%<%f\ %h%m%r%=%{tagbar#currenttag('%s\ ','','f')}%-.(%l,%c%V%)\ %P
Note that:
Spaces must be slash-escaped in the strings you pass to currenttag()...and it's even different between running the command inside vim and putting it in your .vimrc?? Anyway, spaces can be weird, and they're probably something you want when outputting the function name.
It took me some digging but the default statusline is
:set statusline=%<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P
There are several plugins for status line or on-demand with a mapping, e.g.:
http://www.vim.org/scripts/script.php?script_id=1094
http://www.vim.org/scripts/script.php?script_id=2805
http://www.vim.org/scripts/script.php?script_id=1553
My solution is as follows:
set stl=%f%h%m%r\ %{Options()}%=%l,%c-%v\ %{line('$')}
fu! PlusOpt(opt)
let option = a:opt
if option
return "+"
else
return "-"
endif
endf
fu! Options()
let opt="ic".PlusOpt(&ic)
let opt=opt." ".&ff
let opt=opt." ".&ft
if &ft==?"cpp" || &ft==?"perl"
let text = " {" . FindCurrentFunction() . "}"
let opt= opt.text
endif
return opt
fu! FindCurrentFunction()
let text =''
let save_cursor = getpos(".")
let opening_brace = searchpair('{','','}','bWr', '', '', 100)
if opening_brace > 0
let oldmagic = &magic
let &magic = 1
let operators='operator\s*\%((\s*)\|\[]\|[+*/%^&|~!=<>-]=\?\|[<>&|+-]\{2}\|>>=\|<<=\|->\*\|,\|->\|(\s*)\)\s*'
let class_func_string = '\(\([[:alpha:]_]\w*\)\s*::\s*\)*\s*\%(\~\2\|'.operators
let class_func_string = class_func_string . '\|[[:alpha:]_]\w*\)\ze\s*('
let searchstring = '\_^\S.\{-}\%('.operators
let searchstring = searchstring.'\|[[:alpha:]_]\w*\)\s*(.*\n\%(\_^\s.*\n\)*\_^{'
let l = search(searchstring, 'bW', line(".")-20 )
if l != 0
let line_text = getline(l)
let matched_text = matchstr(line_text, class_func_string)
let matched_text = substitute(matched_text, '\s', '', 'g')
let text = matched_text
endif
call setpos('.', save_cursor)
let &magic = oldmagic
endif
return text
endfunction
I'm actually attempting to match the C/C++/Java allowed names for functions. This generally works for me (including for overloaded operators) but assumes that the opening { is at column 0 on a line by itself.
I just noticed today that it fails if included in a namespace {}, even if otherwise formatted as expected.
I use https://github.com/mgedmin/chelper.vim for this. It doesn't needs a tags file, instead it parses the source code on the fly.
Based on #solidak solution (which was already based on another one :)
I wanted to always show the function name in the bottom of the terminal.
But I had some problems with very large function which I solved that way:
fun! ShowFuncName()
echohl ModeMsg
echo getline(search("^[^ \t#/]\\{2}.*[^:]\s*$", 'bWn'))[:winwidth('%')-3]
echohl None
endfun
augroup show_funcname
autocmd CursorMoved * :call ShowFuncName()
augroup end
In Intellij Idea, there's a feature. Let's say I have used a variable myCamelCase somewhere in my code. Then if I type mCC and press Ctrl-Enter or some such key combination, it expands to myCamelCase. Is there something similar in Vim?
Okay, forgive me for answering twice, but since my first attempt missed the point, I'll have another go. This is more complicated than I thought, but possibly not as complicated as I have made it (!).
This is now modified to suggest all matching variable names.
First of all, here's a function to generate the 'mCC' abbreviation from the 'myCamelCase' string:
function! Camel_Initials(camel)
let first_char = matchstr(a:camel,"^.")
let other_char = substitute(a:camel,"\\U","","g")
return first_char . other_char
endfunction
Now, here's a function that takes an abbreviation ('mCC') and scans the current buffer (backwards from the current line) for "words" that have this abbreviation. A list of all matches is returned:
function! Expand_Camel_Initials(abbrev)
let winview=winsaveview()
let candidate=a:abbrev
let matches=[]
try
let resline = line(".")
while resline >= 1
let sstr = '\<' . matchstr(a:abbrev,"^.") . '[a-zA-Z]*\>'
keepjumps let resline=search(sstr,"bW")
let candidate=expand("<cword>")
if candidate != a:abbrev && Camel_Initials(candidate) == a:abbrev
call add( matches, candidate )
endif
endwhile
finally
call winrestview(winview)
if len(matches) == 0
echo "No expansion found"
endif
return sort(candidate)
endtry
endfunction
Next, here's a custom-completion function that reads the word under the cursor and suggests the matches returned by the above functions:
function! Camel_Complete( findstart, base )
if a:findstart
let line = getline('.')
let start = col('.') - 1
while start > 0 && line[start - 1] =~ '[A-Za-z_]'
let start -= 1
endwhile
return start
else
return Expand_Camel_Initials( a:base )
endif
endfunction
To make use of this, you must define the "completefunc":
setlocal completefunc=Camel_Complete
To use insert-mode completion, type CTRL-X CTRL-U, but I usually map this to CTRL-L:
inoremap <c-l> <c-x><c-u>
With this code in your vimrc you should find that typing mCC followed by CTRL-L will make the expected replacement. If no matching expansion is found, the abbreviation is unchanged.
The code isn't water-tight, but it works in all the simple cases I tested. Hope it helps. Let me know if anything needs elucidating.
There is a plugin for this in Vim called vim-abolish. Use the map crc to expand to camel case.