Kevin
Kevin

Reputation: 1569

How to treat leading spaces as tabs in Vim when navigating?

Basically I have the following settings for PSR-2 code compliance:

set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
set smarttab

PSR-2 requires indentions to be 4 spaces. That's fine, but I'm used to real tabs instead of spaces, so if I'm at the beginning of a line, and I move right, instead of moving to the first indented character, it moves over one space at a time.

Is there any way to make vim treat these leading spaces in the same way, that is, to "jump" to the first non-space character when navigating in normal mode and insert mode?

I know I can use ^ to place the cursor to the first non-whitespace character, but I'm not used to that, and it's not as convenient as simply navigating.

Upvotes: 0

Views: 289

Answers (2)

Brett Y
Brett Y

Reputation: 7678

I think you would be better served getting used to utilizing vims more powerful movement commands, such as ^.

That being said, here is one way you could achieve what you want.

nnoremap <right> :silent call SkipSpace()<cr>
function! SkipSpace()
  let curcol = col('.')
  execute "normal ^"
  let hatcol = col('.')

  if curcol >= hatcol
    " move one space right
    let newcol = curcol + 1
  elseif curcol + 4 > hatcol
    " move to the start of the next word if it is less than 4 spaces away
    let newcol = hatcol
  else 
    " move 4 spaces right
    let newcol = curcol + 4
  endif

  execute "normal " . newcol . "|"

endfunction

P.S. For a bit of fun check out :help |

Upvotes: 1

mattn
mattn

Reputation: 7723

Put below into your vimrc

function! s:super_left()
  return getline('.')[:col('.')] =~ '^\s\+$' ? 'w' : 'l'
endfunction
augroup SuperLeft
  au!
  autocmd FileType php nnoremap <expr> l <sid>super_left()
augroup END

Upvotes: 1

Related Questions