开发者

Vim: Call an ex command (set) from function?

开发者 https://www.devze.com 2022-12-24 20:32 出处:网络
Drawing a blank on this, and google was not helpful. Want to make a function like this: function JakPaste()

Drawing a blank on this, and google was not helpful.

Want to make a function like this:

function JakPaste()
        let tmp = :set paste?
        if tmp == "paste"
                set nopaste
        else
                set paste
        endif
endfunction

map <F2> :call JakPaste()<CR>

However this does not work. I have isolat开发者_StackOverflow中文版ed the broken line:

function JakPaste()
        let tmp = set paste?
endfunction

map <F2> :call JakPaste()<CR>

Pressing F2 results in this error:

Error detected while processing function JakPaste:
line    1:
E121: Undefined variable: set
E15: Invalid expression:  set paste?
Hit ENTER or type command to continue

How should I call an ex command (set) from a vim function?

This seems somewhat relevant however I still don't get it.


The reason this doesn't work is that you're trying to run a command in an expression - those are different things. The ? construct you used just causes vim to echo the value of the option; this isn't the same as a function returning the value. To be clear: the problem isn't that you're calling an ex command from a function - every other line of the function is an ex command - it's that you're calling the ex command in an expression.

But that's not the right way to carry out the task you're attempting here. Here's the shortest way, thanks to rampion's comment:

set paste!

Now, if you ever need something smarter than just inverting a boolean, you can use & to turn an option name into a usable variable. Here are two ways to use that:

" still a function, good for taking extra action (here, printing notification)"
function TogglePaste()
    if (&paste)
        set nopaste
        echo "paste off"
    else
        set paste
        echo "paste on"
    endif
endfunction

" just set the variable directly"
let &paste = !&paste
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号