Start Vim in insert mode for new files

2017-09-08 16:53:54

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 an 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.

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

  • 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:

    :h autocmd-events

    :h BufNewFile

    :h :startinsert

    2017-09-08 19:12:38