Moving to the beginning of line within Vim insert mode

While typing I realize that I need to move to the beginning of the line. Usually I use Esc and I. But I am wondering if there is another way to move to the beginning of the line in the insert mode.

2

5 Answers

You can use Ctrl-o which switches to normal mode for one command. This allows you to do movements, such as:

  • Ctrl-o, 0 beginning of line
  • Ctrl-o, $ end of line
  • Ctrl-o, f, y find first y in sentence

I will remap some shortcut keys in my vimrc, most of them are cursor moving under the Insert mode.

For example, I will use the Emacs-Like (as same as in Linux Terminal) shortcut:

map <C-a> <ESC>^
imap <C-a> <ESC>I
map <C-e> <ESC>$
imap <C-e> <ESC>A
inoremap <M-f> <ESC><Space>Wi
inoremap <M-b> <Esc>Bi
inoremap <M-d> <ESC>cW

That means:

  • Ctrl+a: Go to beginning of the line [Normal Mode && Insert Mode]
  • Ctrl+e: Go to end of line [Normal Mode && Insert Mode]
  • Alt+f: Backward a word [Insert Mode]
  • Alt+b: Forward a word [Insert Mode]
  • Alt+d: Delete a word (backward) [Insert Mode]

Of cause, vim has default shortcut key for Delete a word (forward) [Insert Mode], that is Ctrl+w

The Home key works in Vim while in insert mode.

I find this package quite helpful to setup emacs bindings in vim insert mode:

Copying the code from there as suggested by members:

" insert mode
imap <C-p> <Up>
imap <C-n> <Down>
imap <C-b> <Left>
imap <C-f> <Right>
imap <C-a> <C-o>:call <SID>home()<CR>
imap <C-e> <End>
imap <C-d> <Del>
imap <C-h> <BS>
imap <C-k> <C-r>=<SID>kill()<CR>
function! s:home() let start_column = col('.') normal! ^ if col('.') == start_column normal! 0 endif return ''
endfunction
function! s:kill() let [text_before, text_after] = s:split_line() if len(text_after) == 0 normal! J else call setline(line('.'), text_before) endif return ''
endfunction
function! s:split_line() let line_text = getline(line('.')) let text_after = line_text[col('.')-1 :] let text_before = (col('.') > 1) ? line_text[: col('.')-2] : '' return [text_before, text_after]
endfunction
1

While in Insert mode, the Home key moves the cursor to the beginning of the line. If in Normal mode, "SHIFT+I" moves the cursor to the line's first position, changing mode also to Insert mode.

I note that the Insert mode CTRL+o and :(linenumber) is still a viable means to jump directly another line from insert mode to insert mode, however practical/impractical you could find it. It works.

$>vim --version VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Feb 21 2021 23:02:54) MS-Windows 64-bit console version Included patches: 1-2541 Compiled by appveyor@APPVYR-WIN Huge version without GUI.:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like