Move cursor to beginning of non-whitespace characters in a line in Vim

49

10

In Vim, is there a way to move the cursor to the beginning of non-whitespace characters in a line? For instance, how can I move the cursor to the "S" in the second line below?

First line
    Second line

If it matters, I primarily use MacVim, but I'd also like to be able to do this from the console.

Thanks!

Joe Mornin

Posted 2011-06-23T14:02:40.573

Reputation: 1 399

Answers

59

If I understand correctly - from :h ^:

^ To the first non-blank character of the line.
  |exclusive| motion.

(in contrast to 0, which gets you to the beginning, regardless of whitespace or not)

slhck

Posted 2011-06-23T14:02:40.573

Reputation: 182 472

1+1 on the 0 comment – Roy Truelove – 2017-09-01T17:01:45.637

48

Instead of pressing ^ you can press _(underscore) to jump to the first non-whitespace character on the same line the cursor is on.

+ and - jump to the first non-whitespace character on the next / previous line.

(These commands only work in command mode, not in insert mode.)

Ben

Posted 2011-06-23T14:02:40.573

Reputation: 581

8

Also possibly useful: + and - will move the cursor up or down, respectively, to the first non-blank character.

shmup

Posted 2011-06-23T14:02:40.573

Reputation: 190

4

below is a snippet from by .vimrc
^[[1~ is created by pressing ctrl+v and Home

"jump to first non-whitespace on line, jump to begining of line if already at first non-whitespace
map <Home> :call LineHome()<CR>:echo<CR>
imap <Home> <C-R>=LineHome()<CR>
map ^[[1~ :call LineHome()<CR>:echo<CR>
imap ^[[1~ <C-R>=LineHome()<CR>
function! LineHome()
  let x = col('.')
  execute "normal ^"
  if x == col('.')
    execute "normal 0"
  endif
  return ""
endfunction

Andrew Sohn

Posted 2011-06-23T14:02:40.573

Reputation: 141

Thanks, this is what I was searching for. This behaviour is common on editors nowadays (Atom/VSCode/Sublime to name a few) and I've gotten used to it... – YoYoYonnY – 2016-11-30T19:13:19.803

0

Expanding on Andrew Sohn's answer, if you'd like to use 0 for this behavior, just wrap it like so:

function! LineHome()
  let x = col('.')
  execute "normal ^"
  if x == col('.')
    unmap 0
    execute "normal 0"
    map 0 :call LineHome()<CR>:echo<CR>
  endif
  return ""
endfunction 

user2448373

Posted 2011-06-23T14:02:40.573

Reputation: 1

-1

I just remap the 0 key to ^

Edit your ~/.vimrc

set visualbell t_vb=
map 0 ^

Sunding Wei

Posted 2011-06-23T14:02:40.573

Reputation: 99