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

老子叫甜甜 提交于 2019-12-11 04:06:47

问题


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 isolated 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.


回答1:


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


来源:https://stackoverflow.com/questions/2540524/vim-call-an-ex-command-set-from-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!