10

I can search for whole words like this

/\<search term\>

\< and \> match left and right word boundaries respectively.

But how can I insert those automatically? They are awkward to type out.

11

There are two different ways to do this.

  1. You can insert those and the word currently under your cursor with *. So for example, if your cursor is on "hello", and you press asterisk, vim will treat that the same as /\<hello\><cr>. This is generally going to be the fastest way (more info). However, there's one downside. If you don't have the word you want to search for in your buffer, then you can't really navigate to that word and press *. And doing something like iHello<esc>*u isn't really that much better than just /\<Hello\>. So this is only more efficient when you are near that word. If that happens a lot, you could try method 2:

  2. Create a mapping. Since we don't want to overwrite /, this is the perfect use case for <leader>. I personally would do this (put in .vimrc):

    nnoremap <leader>/ /\<\><left><left>
    

    which will insert the brackets and position your cursor between them so you can type out the word you want to search.

| improve this answer | |
1

Another possibility is to add a commandline-mode mapping with :cmap to add \< and \>; so then you'd type hello, press e.g. <F1>, and that will transform it to \<hello\>.

A simple version might look like:

cnoremap <expr> <F1> index(['/', '?'], getcmdtype()) is -1 ? "\<F1>" : "\<Home>\\<\<End>\\>"

It just sends <Home>\<<End>\>. This is a bit naïve since it doesn't check whether there already are angled brackets, and it frobs with the cursor position. A better, but longer, version might look like:

fun! s:wrap()
    let l = getcmdline()
    let pos = getcmdpos()

    " Remove
    if l[:1] is '\<' && l[-2:] is '\>'
        call setcmdpos(pos - 2)
        return l[2:len(l)-3]
    endif

    " Add
    if l[:1] isnot '\<'
        let l = '\<' . l
        let pos += 2
    endif
    if l[-2:] isnot '\>'
        let l .= '\>'
    endif
    call setcmdpos(pos)
    return l
endfun

cnoremap <expr> <F1> index(['/', '?'], getcmdtype()) is -1 ? "\<F1>" : "\<C-\>e<SID>wrap()\<CR>"

With <C-\>e the return value of a function is inserted, the function removes \< and \> if they exist, or adds them if they don't. If also preserves the cursor position.

| improve this answer | |

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.