0

I want to conveniently remove an accidentally placed tab while using vim. The solution that jumped out to me is making an insert-mode mapping to the following vim function:

function DeleteTab()
  redir => l:numSpaces "captures output of set
  set tabstop?
  redir END
  "Strip off non-numerical output of 'set tabstop?' 
  let l:numSpaces = substitute(l:numSpaces, "tabstop=", "", "") 
  let l:numSpaces = substitute(l:numSpaces, " ", "", "g")
    "all echom lines are for debugging purposes
  echom "1" 
  if l:numSpaces > 0
     echom "2"
  while 1:numSpaces > 0
     execute "normal i<bs>"
     let l:numSpaces = l:numSpaces - 1
  endwhile
endfunction

In addition to not doing what I intended, the result of calling this function is "1" in my messages, but not "2". This means that l:numSpaces is not being interpreted as a number. How do I do the equivalent of casting in vimscript. Also, am I missing a more easy approach?

2 Answers 2

3

Instead of doing the redir just use &tabstop the ampersand gets the value and places it in the variable.

let l:numSpaces = &tabstop

The next problem you have is with this line

while 1:numSpaces > 0

You wrote a 1 (one) instead of l (lowercase L)

So the fixed function looks something like this.

function! DeleteTab()
    let l:numSpaces = &tabstop
    echom "1" 
    if l:numSpaces > 0
        echom "2"
    endif
    while l:numSpaces > 0
        execute "normal i<bs>"
        let l:numSpaces = l:numSpaces - 1
    endwhile
endfunction

Also this function is kinda pointless. I believe the behavior you want should be achieved if you set the following (or to what ever value you want)

set tabstop=4
set softtabstop=4
set shiftwidth=4

Hitting the backspace key should go back a full tab if you insert an accidental tab.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to access the value of an option in vimscript, you can use the syntax &option (see :help expr-option). That simplifies the first half of your function to

let numSpaces = &tabstop

As far as undoing an accidental tab, all that should require is pressing Backspace, unless you aren't inserting tab characters.

If you mean you want to "remove a level of indentation" instead of "remove a tab", then you should use the builtin command for that, pressing Ctrl+d in insert mode. Similarly, you can use Ctrl+t to add a level of indentation to the current line. Both of these work regardless of where your cursor is in the current line, unlike trying to manage the indentation manually with Backspace, as well as doing the Right Thing based on your 'shiftwidth', 'expandtab', and 'tabstop' settings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.