Monday, September 17, 2012

Re: Mappings for reusing result of function without defining additional function

Hi,

skeept wrote:
> When using a function from a plugin, say F1() I want to check if the result is not the empty string, if it is call some other function, F2(), if it is not execute the string resulting from function F1().
> Calling F1() has a side effect like moving the cursor around so I don't want to call it more than once per time I use the mapping.
>
> In order to do this I create and additional function
>
> function F1_wrap()
> let g:f1_res = F1()
> return g:f1_res
> endfunction
>
> and then define the mapping as
> inoremap <c-a> <c-r>=(F1_wrap() == '') ? F2() : g:f1_res <cr>
>
> This is of course not a big deal, but I was wondering if there is there a way of doing this without creating an additional function?

write a helper function and pass it the the second function as a string,
including the pair of parentheses needed to call the function. Your
helper function can then evaluate the string when needed.

function F1_with_default(default_expr)
let res = F1()
return res == '' ? res : eval(a:default_expr)
endfunction

inoremap <c-a> <c-r>=F1_with_default('F2()')<cr>

It might also be possible to pass the second function as a function
reference (see :help Funcref), but I have not used them yet. So the
following code is untested:


function F1_with_default(default_func)
let res = F1()
return res == '' ? res : a:default_func
endfunction

inoremap <c-a> <c-r>=F1_with_default(function('F2'))<cr>

Regards,
Jürgen

--
Sometimes I think the surest sign that intelligent life exists elsewhere
in the universe is that none of it has tried to contact us. (Calvin)

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: