Wikia

Vim Tips Wiki

Watchlist Recent changes

Smart home

Tip 315 Printable Monobook Previous Next

created August 14, 2002 · complexity advanced · author Alex A. Naanou · version 5.7


Put the following in your vimrc. When you press the Home key, the cursor will move to the first nonblank character on the line, or, if already at that position, the cursor will move to the first character.

function! SmartHome()
  let s:col = col(".")
  normal! ^
  if s:col == col(".")
    normal! 0
  endif
endfunction
nnoremap <silent> <Home> :call SmartHome()<CR>
inoremap <silent> <Home> <C-O>:call SmartHome()<CR>

See also Edit

  • homeLikeVC++.vim provides the same feature in a slightly different way. Mappings for visual mode, and a smart-<End> are also provided.

CommentsEdit

If you don't mind smashing a mark ('h in this case), you can use the map in visual mode, too:

vnoremap <silent> <Home> <Esc>:call <SID>SmartHome()<CR>mhgvg`h

There is no need to smash any mark if we:

  • return what must be executed instead of playing with :normal!
  • and then use @=

See the latest version of homeLikeVC++ (the link has been updated)


We don't need to use functions, :normal!, or @= if we use <expr> maps. These maps should work properly in normal mode, visual mode, insert mode, select mode, and operator-pending mode:

noremap  <expr> <Home> (col('.') == matchend(getline('.'), '^\s*')+1 ? '0'  : '^')
noremap  <expr> <End>  (col('.') == match(getline('.'),    '\s*$')   ? '$'  : 'g_')
vnoremap <expr> <End>  (col('.') == match(getline('.'),    '\s*$')   ? '$h' : 'g_')
imap <Home> <C-o><Home>
imap <End>  <C-o><End>

Pages on Vim Tips Wiki

Add a Page
1,601pages on
this wiki

Latest Photos

Add a Photo
66photos on this wiki
See more >

Recent Wiki Activity

See more >

Around Wikia's network

Random Wiki