When searching for a phrase in hard-wrapped text, one wants newlines to be treated as spaces. Can one have that happen? Saying /the\_sphrase\_sI\_sseek is a bit awkward.

  • 2
    See this answer: unix.stackexchange.com/a/11848 for a custom function (and command) that does what you want. Adjust to your taste.
    – VanLaser
    Feb 26 '16 at 11:52
  • 1
    The problem with this solution is that it can't make use of incremental search. But cmap <m-space> \_s\+ works well (in nvim).
    – Toothrot
    Feb 26 '16 at 15:53
  • Whatever floats your boat is ok :)
    – VanLaser
    Feb 26 '16 at 17:19

You can automatically replace a space with \_s when searching with:

cnoremap <expr> <Space> index(['/', '?'], getcmdtype()) > -1 ? '\_s' : ' '

Because cnoremap is applied to all the commandline (and not just search), we need an expression mapping to check if we're searching or in another commandline mode (e.g. :).

Because you probably don't always want to search like this, you can trigger this newline-insensitive mode with something like:

fun! StartNewlineSearch()
    cnoremap <expr> <Space> index(['/', '?'], getcmdtype()) > -1 ? '\_s' : ' '

    " Unmap both <Space> and this same mapping when pressing <CR>
    cnoremap <CR> <CR>:cunmap <lt>Space><CR>:cunmap <lt>CR><CR>:cunmap <lt>Esc><CR>

    " And the same for <Esc>
    cnoremap <Esc> <Esc>:cunmap <lt>Space><CR>:cunmap <lt>CR><CR>:cunmap <lt>Esc><CR>

nnoremap // :call StartNewlineSearch()<CR>/

When pressing // it maps <Space> to \_s, and it unmaps it when pressing <CR> or <Esc>.

You could also map this to a key to toggle the two "modes":

let g:search_mode = 0
fun! ToggleMode()
    if g:search_mode == 0
        cnoremap <expr> <Space> index(['/', '?'], getcmdtype()) > -1 ? '\_s' : ' '
        let g:search_mode = 1
        cunmap <Space>
        let g:search_mode = 0
    return getcmdline()

cnoremap <C-@> <C-\>eToggleMode()<CR>

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.