0

In Vim, it would be cool to search for the currently highlighted text in a search engine of your choice. Especially with all the AI search engines that are appearing on the scene.

This kinda works, but the text is not urlencoded:

:'<,'>y|call system('firefox https://www.gnod.com/search/ai?q='.shellescape(@*))

I wonder if there is a way to urlencode it?

no_gravity
  • 579
  • 1
  • 3
  • 14
  • https://www.danielbigham.ca/cgi-bin/document.pl?mode=Display&DocumentID=1053 , https://gist.github.com/atripes/15372281209daf5678cded1d410e6c16 Found in https://www.google.com/search?hl=en&pws=0&q=vim+encode+url – phd Jun 08 '23 at 13:34
  • 1
    Other options that can probably be plugged in can be found at https://stackoverflow.com/questions/296536/how-to-urlencode-data-for-curl-command (from second answer onwards) or https://stackoverflow.com/questions/11876353/url-encoding-a-string-in-bash-script. – Marijn Jun 08 '23 at 13:38
  • @phd: I hope to keep it a slick oneliner and avoid to use a massive script like those that can be found via Google. – no_gravity Jun 08 '23 at 17:09
  • @Marijn: Yes, passing it to curl or jq could be a good option. But how do you pass a multiline string to a shell command? – no_gravity Jun 08 '23 at 17:10
  • 2
    There is no native `urlencode()` function but Tim Pope has [this](https://github.com/tpope/vim-unimpaired/blob/master/plugin/unimpaired.vim#L460-L463) in a plugin of his. – romainl Jun 08 '23 at 17:33
  • @romainl: Holy moly, this works! :'<,'>y|call system('firefox https://www.gnod.com/search/ai?q='.substitute(iconv(@*, 'latin1', 'utf-8'),'[^A-Za-z0-9_.~-]','\="%".printf("%02X",char2nr(submatch(0)))','g')) – no_gravity Jun 09 '23 at 10:23
  • Yeah, but that's one hell of one-liner. – romainl Jun 09 '23 at 10:38
  • @romainl Yup, but maybe thats the shortest possible. – no_gravity Jun 09 '23 at 17:57
  • @no_gravity you should post an answer if you solved your problem. – romainl Jun 15 '23 at 06:25
  • @romainl: Done. – no_gravity Jun 16 '23 at 07:53

1 Answers1

0

This works:

:'<,'>y|call system('firefox gnod.com/search/ai?q='.substitute(iconv(@*, 'latin1', 'utf-8'),'[^A-Za-z0-9_.~-]','\="%".printf("%02X",char2nr(submatch(0)))','g'))
no_gravity
  • 579
  • 1
  • 3
  • 14