开发者

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 result开发者_JAVA技巧s, 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() 

```


I believe this works from inside a function (to just enable highlighting and nothing more):

call feedkeys(":\<C-u>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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜