Larvus Koji
Larvus Koji

Reputation: 13

Prevent using B or b from jumping to previous line in vim

I found the following code on SO and it works great for using E to jump to words and stopping at the end of the line like this: nnoremap <expr> E getline('.')[col('.') - 1:] =~# '\s\S' ? 'E' : (col('.') + 1 == col('g_') ? 'E' : '$').
But I only recently started dabbing into vimscripts and can't get it to work for going backwards with b/B. I attempted to do something like this but didn't work as it doesn't stop at the start of the line:

nnoremap <expr> B getline('.')[col('.') + 1:] =~# '\S\s' ? 'B' : (col('.') - 1 == col('^') ? 'B' : '^')

Upvotes: 0

Views: 80

Answers (1)

j1-lee
j1-lee

Reputation: 13939

I suggest the following:

nnoremap <expr> B strpart(getline('.'), 0, col('.') - 1) =~ '^\s*$' ? '0' : 'B'

strpart(getline('.'), 0, col('.') - 1) picks up the substring left to the current cursor position. If this is empty or consists only of whitespaces (i.e., when B would normally jump to the previous line), then B is mapped to 0, i.e., it goes to the first character of the line without jumping to the previous line. Otherwise, B behaves like the original B.

Upvotes: 1

Related Questions