1

Assume autoindent is set, and you have the buffer below. Note the cursor is represented as I.

for i in range(1, 6):
    print(i)I

When you hit Enter key, you get this.

for i in range(1, 6):
    print(i)
    I

Question: is there any simple way to move the cursor back to the place before the press of Enter key? These are solutions but too complicated:

  • Five presses of backspace key
  • Ctrl+d (decrease indent by one) and one press of backspace
  • Esc (exit insert mode) and k (move cursor up) and Shift+a (append to current line).

If it is possible, I would like to realize that without exiting insert mode. In the other words, I would like to avoid Esc, Ctrl+o (execute one normal command), and so on.

2 Answers 2

2

ctrl w w (hold ctrl, don't release)

Note that you need to set :h 'backspace' to indent,eol,start for this to work .

You can also use <backspace> or <c-u> instead of <c-w> if you want.

The behavior is described in :h i_backspacing .

4
  • Thank you. This is exactly what I wanted.
    – ynn
    Commented Jul 6, 2019 at 3:34
  • <C-u> also works
    – D. Ben Knoble
    Commented Jul 6, 2019 at 13:06
  • 1
    Control-u twice
    – D. Ben Knoble
    Commented Jul 7, 2019 at 1:44
  • @D.BenKnoble Thanks, updated.
    – dedowsdi
    Commented Jul 7, 2019 at 2:04
0

You can create a mapping to be able to use a single backspace to return to the previous line and undo the autoindent.

The 'autoindent' documentation says:

If you do not type anything on the new line except <BS> or CTRL-D and then type <Esc>, CTRL-O or <CR>, the indent is deleted again.

Using CTRL-O and a normal mode command that does nothing is convenient, since it will not have unwanted side effects where there's no autoindent, but it will still do the job where there's an autoindent.

For a command that does nothing, we can use :<CR>, briefly entering command mode but not entering any command.

This mapping should do the job:

inoremap <bs> <c-o>:<cr><bs>

With this mapping in place, pressing a single <BS> after a return that triggers an autoindent will get the cursor back to the end of the previous line. Elsewhere, <BS> will work as it normally does.

1
  • 1
    Thank you, but that doesn't work on my enviroment (VIM 8.1 compiled from source on Linux Mint, VIM 8.0 on Raspbian, and VIM 8.1 without .vimrc on FreeBSD). For now, I use inoremap <C-s> <Esc>kA (though we first have to disable the "freeze" functionality of Ctrl+s).
    – ynn
    Commented Jul 6, 2019 at 9:57

Your Answer

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

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