6

I mostly use Vim to edit configuration files so I understand why it starts in normal mode. But I also use vi mode for the REPL (bash, zsh, ipython, etc.) and the shell always starts in insert mode (this makes sense because you just want to start typing a command).

For the same reason, when I open a new empty file vim foo.txt, I want to be in insert mode. So I'm looking for a vimrc function that checks if the file is empty and then put me in insert mode.

In this way I can be consistent across the terminal. When there aren't text objects I know I'm in insert mode.

isar
  • 163
  • 1
  • 4

2 Answers2

13

You need to add this to your vimrc:

autocmd BufNewFile * startinsert

The autocommand creates a command which is executed on a specific event.

Here the event is BufNewFile the doc descibes it has:

When starting to edit a file that doesn't exist. Can be used to read in a skeleton file.

The * is here to execute the command on every new file (not a specific filetype or name)

And the command to be executed is startinsert which starts insert mode.

Note that it will also work for new files edited from vim with e foo.txt for example.

See:

statox
  • 49,782
  • 19
  • 148
  • 225
  • Anyway, when the background is set (ex. set background=dark) in the .vimrc it opens the new file in insert mode with -- INSERT -- in the first line. – isar Sep 08 '17 at 15:54
  • I don't understand how this is related? – statox Sep 08 '17 at 16:09
  • I try to explain: only when I have both autocmd BufNewFile * startinsert and set background=dark in my .vimrc if I open a new file vim foo.txt, the text -- INSERT -- will appear in the first line, so I had to remove set background=dark from my .vimrc. – isar Sep 08 '17 at 16:19
  • @isar I'm sure there's another reason. Do you set the background before or after the autocmd? – Maya Sep 08 '17 at 17:59
  • @isar the background option shouldn't have an impact on that, have a look at this really good question to debug that :) – statox Sep 08 '17 at 19:01
  • @isar Is it actually present in the file, or just on the screen? i.e. does it go away if you e.g. exit insert mode and press ctrl-l? – Random832 Sep 08 '17 at 19:48
  • @Random832 yes, it does go away if I press Esc and then Ctrl+l. So it is actually on the screen. If I start typing it also goes away progressively and get overridden from the characters I insert. Thank you – isar Sep 09 '17 at 06:49
  • @isar There's probably something wrong with your term or termcap settings. You should open another question for this issue. – Random832 Sep 09 '17 at 14:39
1

vim -c 'startinsert'

Will start Vim in insert mode pass it a file and it will open that file in insert mode.

The easiest way is to make save this as an alias in your terminal config.

Example: alias vim="vim -c 'startinsert' "

Gustav Blomqvist
  • 791
  • 1
  • 6
  • 18