2

In IntellijIDEA, if my cursor is at the start of a line, instead of backspace deleting one indent or whitespace at a time, it deletes all tabs and whitespace and moves the cursor to the end of the previous line. How can I setup this behaviour in Vim?

1 Answer 1

2

This should do the trick:

function! MyDeleteAction()
    " Get the current position and the position of the first char
    let cursorPosition=getpos(".")
    normal ^
    let firstChar=getpos(".")

    " If the cursor is before the first char, go to the upper line
    if cursorPosition[2] < firstChar[2]
        normal! y$0Dk$
        let cursorPosition=getpos(".")
        normal! p
    endif

    " Go back to the correct position
    call setpos('.', cursorPosition)
endfunction

inoremap <silent> <backspace> <backspace><Esc>:call MyDeleteAction()<CR>a

The last line remaps backspace in insert mode so that it will first delete a character as usual and then call MyDeleteAction().

The function MyDeleteAction() tests if the cursor is on the first character of the line:

  • If it is not the cursor stays at the same position
  • If it is we yank the end of the current line, delete the current line, paste the yanked end of the line to the upper line and put the cursor before the pasted text.

The main drawback here is that the function will change your unnamed register when it yanks the line so you might want to add a mechanism to save the state of this register and restore it.

Your Answer

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

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