简体   繁体   English

如何打开vim脚本中的搜索突出显示?

[英]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. 从脚本开始,然后vim进行搜索但不突出显示结果,即使是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) 呼叫搜索(l:searchString)

call matchadd('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. (当从函数内部运行时)它确实高亮了我想要搜索的单词,但是n / N不会在它们之间循环。 Also when I performed a new search the "l:serachStirng" pattern still remained highlighted. 此外,当我执行新搜索时,“l:serachStirng”模式仍然保持突出显示。 This answer on this link worked much better 这个链接上的答案效果更好

Vim search and highlighting control from a script Vim从脚本中搜索并突出显示控件

Which gave me: 哪个给了我:

let @/ = l:searchString 让@ / = l:searchString

then run 然后运行

normal n 正常的

outside the funciton (so the highlighting is done immediately without the user needing to press n) 在功能之外(所以突出显示是在没有用户需要按n的情况下立即完成的)

To turn on, press ESC type :set hls 要打开,请按ESC:set hls

To turn off, press ESC type :set nohls 要关闭,请按ESC:set nohls

Found answer here: http://vim.1045645.n5.nabble.com/highlighting-search-results-from-within-a-function-tt5709191.html#a5709193 在这里找到答案: 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()". 并使用以下代替“:call XXXX()”。

:let @/ = XXXX() 

``` ```

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

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

You need to put this in your .vimrc file 您需要将它放在.vimrc文件中

" 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" .vimrc文件通常位于您的主目录中,或者您可以使用“locate .vimrc”找到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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