简体   繁体   中英

subfunctions in vim

I created a lot of functions in menu.vim.

I noted that in many functions the same code is used that's why I decided to clean up my file with the use of subfunctions.

pe this is code what often returns in my functions:

let zoek = @/    
if a:type == "'<,'>"    
 let r = substitute(zoek, '\\%V', '', 'g')    
elseif a:type == "%"    
 let r = zoek    
endif    

let a = substitute(r, '\', '', 'g')      

if matchstr(d, '>') == '>' || matchstr(d, '<') == '<'     
 let e = substitute(d, '\zs>\(\d\+\)%<\ze', '\1-', 'g')     
endif

How can I create a subfunction from it? How can I invoke it?
Does Vim have subfunctions?

You can have «local» functions by defining them in the dictionary: in the following code

function MyFunc()
    let d={}
    function d.function()
        echo "Foo"
    endfunction
    call d.function()
endfunction

function d.function is accessible only inside s:MyFunc and is destroyed after s:MyFunc exits. I put «local» in quotes because d.function is really global function named 42 (or another number, it does not matter). It cannot be called without a reference to it and the only way to create a reference is to use function dict.key() (references may be copied after creation, but you can't create a reference using call to function() , though it is possible for MyFunc : function("MyFunc") ). Note that number (in this case 42) is incremented each time you create a function and I know neither what is the maximum number nor what will happen when it will be reached. I personally use dictionary functions because they have two other advantages:

  1. Dictionary function defined inside a script-local dictionary cannot be reached without a debugger or explicit passing the function reference (possibly as a part of its container) somewhere.
  2. If more then one function is defined inside a dictionary in order to purge them all you need is to unlet this dictionary. Useful for reloading plugins.

There is only one type of function in Vimscript, but I'm not sure if this is what you are already using in your menu.vim. A user-defined function is defined thus:

    function! MyNewFunction()
        " your code here
    endfunction

You can then call this function elsewhere in your scripts (and inside other functions) using

    call MyNewFunction()

Or set a variable equal to the return value of your function using

    let my_variable = MyNewFunction()

Of course this is an incredibly simplistic overview, since you say your are already using functions. Much more information, including the use of variables, here:

    help user-functions

Apologies if I have not answered your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM