Skip to content

Instantly share code, notes, and snippets.

@reegnz
Last active December 17, 2021 23:11
Show Gist options
  • Save reegnz/1cc931ba17508b5c2e12aaff6babfcb1 to your computer and use it in GitHub Desktop.
Save reegnz/1cc931ba17508b5c2e12aaff6babfcb1 to your computer and use it in GitHub Desktop.
Web search from vim

Vim web search using movements to select the search text

With the vim code below, you can perform a web search (Google in the example).

Typing v2wss will visually select 2 words and then open a google search with those 2 words. Typing ss2w will perform the same as above, but in normal mode.

" Search Google {{{
" see :h map-operator for how this is implemented
function BrowserSearch(type = '', ...)
if a:type == ''
set opfunc=BrowserSearch
return 'g@'
endif
let sel_save = &selection
let reg_save = getreginfo('"')
let cb_save = &clipboard
let visual_marks_save = [getpos("'<"), getpos("'>")]
try
set clipboard= selection=inclusive
let commands = #{line: "'[V']y", char: "`[v`]y", block: "`[\<c-v>`]y"}
silent exe 'noautocmd keepjumps normal! ' .. get(commands, a:type, '')
let text = getreg('"')
let url = g:web_search_url .. text
call netrw#BrowseX(url, 0)
finally
call setreg('"', reg_save)
call setpos("'<", visual_marks_save[0])
call setpos("'>", visual_marks_save[1])
let &clipboard = cb_save
let &selection = sel_save
endtry
endfunction
nnoremap <expr> ss BrowserSearch()
xnoremap <expr> ss BrowserSearch()
let g:web_search_url = "https://google.com/search?q="
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment