Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim function for toggling colorschemes

Tags:

vim

At the moment I'm using two different keys to toogle the colorscheme

map <F8> :colors wombat256 <cr>
map <F9> :colors dimtag <cr>


I want to achieve a toggle behavior like this

function! ToggleDimTags()
if (g:colors_name == "wombat256")
  colors dimtag
else
  colors wombat256
endif
endfunction

My problem is that ToogleDimTags() is resetting the cursor position to the first line on every call, which is undesirable. Any suggestions appreciated.

like image 756
Eric Fortis Avatar asked Jun 04 '11 22:06

Eric Fortis


1 Answers

As discussed in the comments, the problem is that your map calling :execute behaves a little differently, what you probably want is :call instead:

nnoremap <F5> :call ToggleDimTags()

To clarify what @ZyX was saying, :h :exec contains the following text:

                                                         :exe   :execute 
:exe[cute] {expr1} ..   Executes the string that results from the evaluation
                        of {expr1} as an Ex command.
                        [...]

So what :execute really does is evaluating the expression looking for a string that will be executed as an Ex command (also called colon commands). In other words:

exec ToggleDimTags() | " <-- ToggleDimTags() is evaluated and returns 0
exec 0

Which is:

:0

Now, :h :call:

                                                 :cal   :call   E107   E117 
:[range]cal[l] {name}([arguments])
                Call a function.  The name of the function and its arguments
                are as specified with |:function|.  Up to 20 arguments can be
                used.  **The returned value is discarded**.
                [...]

Update

I've been thinking about your function, and using the ternary operator and a bit of :execute magic, you can simplify it up to a point where you discard the extra function:

nnoremap <silent> <F9> :exec "color " .
    \ ((g:colors_name == "wombat256") ? "dimtag" : "wombat256")<CR>

Here, this nnoremap will not produce output (<silent>) and is based on :exec, which is followed by this expression:

"color " . ((g:colors_name == "wombat256") ? "dimtag" : "wombat256")

When g:colors_name is set to wombat256, the expression evaluates to:

"color dimtag"

Or, otherwise:

"color wombat256"

Then either one is evaluated by :exec. Of course you can join the lines (without forgetting to remove the backslash), I did it like this simply to avoid a too long line.

like image 173
sidyll Avatar answered Oct 10 '22 05:10

sidyll