1

When matching in vim there are words, WORDs and blocks among other things. Now for editing code, blocks are useful, words are somewhat useful, but WORDs are mostly useless, because they often include some opening or closing brackets, be it (), {} or [].

So I would like WORDs to match

  • only characters inside the current block, but apart from that
  • complete WORDs (multiple if necessary) and
  • complete blocks (so no unbalanced brackets).

For example consider this line of code:

if (array42[idx + offset] == value) {

with the cursor on the 4. Then it should match array42[idx + offset]. WORD would of course match (array42[idx, which is not useful.

  • Note that there's now an SE site dedicated to vi and its clones: Vi and Vim (still in beta), though vi(m) questions are still welcome here. – Stéphane Chazelas Nov 5 '15 at 10:07
  • @StéphaneChazelas: Thanks for the info. Seems finding the “right” stackexchange site is getting more difficult. I think I’ll leave this question here. – bodo Nov 5 '15 at 10:45
0

I have created a function which visually selects the match through the key combination viW in normal mode.

Please fell free to point out cases I missed. Also there is probably other room for improvement, as I don’t know much about vimscript.

"visually select current programming WORD
function! SelectSensibleWORD()
    "go to beginning of block
    normal! ?^\|[[:space:]({[]
    let l:char = matchstr(getline('.'), '\%' . col('.') . 'c.')
    if -1 != match(l:char, '[[:space:]({\[]')
        normal! l
    endif
    "enter visual mode
    normal! v
    "find brackets or end of the WORD
    normal! /$\|[[:space:]({[\]})]
    while 1
        let l:char = matchstr(getline('.'), '\%' . col('.') . 'c.')
        if -1 != match(l:char, '[({[]')
            "keep brackets balanced
            normal! %
        else
            "don't select more than necessary
            normal! h
            return
        endif
        normal! n
    endwhile
endfunction

nnoremap viW :call SelectSensibleWORD()<CR>

Other commands can then be build upon this:

nmap ciW viWc
nmap diW viWd
nmap yiW mwviWy`w

Pitty, vimscript is not supported by the syntax highlighter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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