简体   繁体   中英

How do I turn on search highlighting from a vim script?

If I do either of the following two:

call search("searchString")

exec "/ searchString"

From a script, then vim does the search but does not highlight the results, even though hlsearch. Doing the same searches from outside a script highlights the results.

Just found out the answer myself:

call search(l:searchString)
call matchadd('Search', l:searchString)

The

feedkeys()

function is the key (pun intended):

call feedkeys("/pattern\<CR>")

or cleaner:

" highlights – or doesn’t – according to 'hlsearch' option
function SearcH(pattern)
    let @/ = a:pattern
    call feedkeys("/\<CR>")
endfunction 

I know this is late. However when I searched for the answer to this problem this page came up. So I feel compelled to help fix it.

call search(l:searchString)

call matchadd('Search', l:searchString)

Did not work for me. (when run from inside a function) It did higlight the words I wanted to search for but n/N wouldn't cycle between them. Also when I performed a new search the "l:serachStirng" pattern still remained highlighted. This answer on this link worked much better

Vim search and highlighting control from a script

Which gave me:

let @/ = l:searchString

then run

normal n

outside the funciton (so the highlighting is done immediately without the user needing to press n)

To turn on, press ESC type :set hls

To turn off, press ESC type :set nohls

Found answer here: http://vim.1045645.n5.nabble.com/highlighting-search-results-from-within-a-function-tt5709191.html#a5709193

```

One solution would be

function! XXXX() 
    execute '/this' 
    return @/ 
endfunction 

and to use the following instead of ":call XXXX()".

:let @/ = XXXX() 

```

我相信这可以从一个函数内部工作(只是启用突出显示,仅此而已):

call feedkeys(":\\<Cu>set hlsearch \\<enter>")

You need to put this in your .vimrc file

" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
  syntax on
  set hlsearch
endif

The .vimrc file is usually located in your home directory, or you can find it using "locate .vimrc"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM