0

In case I have the following line

// Component: <Component name here>                          |

where | is the cursor marker. How can I count, using vimscript, the total number of white spaces before the cursor until the first non space character (> in this case) ?

The aim is to delete all preceding whitespace before cursor, until non first space character (excluding it).

6
  • 1
    Maybe it would be better if you explained what you're trying to accomplish in the bigger picture. Give some context. Counting whitespace is hardly something you do for its own sake.
    – Friedrich
    Commented Jan 9 at 12:08
  • 1
    I updated the question for clearness.
    – xyx
    Commented Jan 9 at 12:13
  • 1
    FWIW, you can use diw without calculating anything, here.
    – romainl
    Commented Jan 9 at 13:19
  • I know it, my purpose was to map C-Backspace to delete previous word or white spaces. I solved anyway.
    – xyx
    Commented Jan 9 at 13:58
  • Add your solution as an answer and remove it from your question.
    – romainl
    Commented Jan 9 at 14:17

2 Answers 2

0

If you want to count the number of white spaces character you could do:

let l = getline('.')
let n = len(l) - match(l, '\s*$')

If you want to count the number of white spaces you could do:

let bnr = bufnr('%')
let winid = bufwind(bnr)

let r = line('.')
let l = getline(r)
let c0 = match(l, '\s*$') - 1
let c1 = len(l) + 1
let n0 = screenpos(winid, r, c0)
let n1 = screenpos(winid, r, c1)
let n = n1 - n0
0

My solution to the question:

inoremap <silent> <expr> <nowait> <C-Del> getline('.')[col('.')-1] == ' ' ? "<C-o>dw" : getline('.')[col('.')-1:] =~ '\w' ? "<C-o>diw" : "<Del>"
inoremap <silent> <expr> <nowait> <C-Backspace> col('.') == 1 ? "<Backspace>" : getline('.')[col('.') - 2] == ' ' ? "<C-o>ge<Right><C-o>dw" : getline('.') == '\s\+' ? "<C-o>g0<C-o>dw" : "<C-o>db"
1
  • How does this solves the problem at hand? Can you explain the logic of this?
    – romainl
    Commented Jan 16 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.