Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Is there any way to have a state variable in VIM? Consider:

" Relative line numbers in Normal mode, absolute in Insert mode. Ctrl-N to toggle 
set relativenumber
autocmd InsertEnter * :set number
autocmd InsertLeave * :set relativenumber
inoremap <C-n> <C-o>:call NumberToggle()<cr>
nnoremap <C-n> :call NumberToggle()<cr>
function! NumberToggle()
  if(useRelNums != 1)
    let useRelNums=1
    set number
  else
    let useRelNums=0
    set relativenumber
  endif
endfunc

Of course, useRelNums is undefined. I would like to keep this variable defined between calls to the NumberToogle() function, i.e. a state variable. How is this done? I'm sure that I could repurpose some other VIM variable as a workaround (such as the state of paste for a bad example) but I would prefer a real solution.

Thanks.

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

you may introduce global variables with let g:use_rel_numbers or let g:use_rel_numbers=1. local variables would be better i think - let b:use_rel_numbers for example and setlocal relativenumber.

share|improve this answer
add comment

You can use the settings themselves as your desired state variables... they're boolean, and exclusive. turning on 'number', turns off 'relativenumber', and vice-versa.

So you could do:

function! ToggleNumbers()
    if &number
        set relativenumber       " was number, now relanum
    elseif &relativenumber
        set norelativenumber     " was relanum, now nothing
    else
        set number               " was nothing, now number
    endif
endfunction

A nice three-state toggle. (triggle?) (troggle?) {shrug} your call...

AND... this interfaces seamlessly with your desired autocmds since they affect the number/relativenumber booleans too... taa daa!

I like triggle...

share|improve this answer
    
@epsilon makes a good point, probably should be setlocal ... really. Uh... I was copying the variable scope style of the author...yeah... that's what I was doing... yeah... But the vim help states that number/relativenumber are local to the window anyways. doesn't hurt though, certainly helps convey the intent that they are PER windows/buffer/thingamabob. –  lornix Jul 1 '12 at 14:15
    
Thanks, lornix. Using the current state of relativenumber won't help as the state is reset when entering / leaving Insert mode. That is why I am trying to do something more elaborate. –  dotancohen Jul 1 '12 at 18:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.