f0bbd308fe01dc607293417775d4009ef0d5c5cf

Author
Robby Russell <robby@planetargon.com>
Committer
Robby Russell <robby@planetargon.com>
Date

Message

Merge pull request #3443 from mcornella/better-web-search-plugin

Refactor and improve web-search plugin

Diff

 1diff --git a/plugins/web-search/web-search.plugin.zsh b/plugins/web-search/web-search.plugin.zsh
 2index 28559deb9d084895371a348ee89585be703b0b33..572427b0b61209f03616ae14cdd9d0b3bf67e109 100644
 3--- a/plugins/web-search/web-search.plugin.zsh
 4+++ b/plugins/web-search/web-search.plugin.zsh
 5@@ -1,43 +1,46 @@
 6 # web_search from terminal
 7 
 8 function web_search() {
 9-  # get the open command
10-  local open_cmd
11-  if [[ "$OSTYPE" = darwin* ]]; then
12-    open_cmd='open'
13-  else
14-    open_cmd='xdg-open'
15-  fi
16+  emulate -L zsh
17+
18+  # define search engine URLS
19+  typeset -A urls
20+  urls=(
21+    google      "https://www.google.com/search?q="
22+    bing        "https://www.bing.com/search?q="
23+    yahoo       "https://search.yahoo.com/search?p="
24+    duckduckgo  "https://www.duckduckgo.com/?q="
25+    yandex      "https://yandex.ru/yandsearch?text="
26+  )
27+
28+  # define the open command
29+  case "$OSTYPE" in
30+    darwin*)  open_cmd="open" ;;
31+    cygwin*)  open_cmd="cygstart" ;;
32+    linux*)   open_cmd="xdg-open" ;;
33+    *)        echo "Platform $OSTYPE not supported"
34+              return 1
35+              ;;
36+  esac
37 
38   # check whether the search engine is supported
39-  if [[ ! $1 =~ '(google|bing|yahoo|duckduckgo)' ]];
40-  then
41+  if [[ -z "$urls[$1]" ]]; then
42     echo "Search engine $1 not supported."
43     return 1
44   fi
45 
46-  local url="http://www.$1.com"
47-
48-  # no keyword provided, simply open the search engine homepage
49-  if [[ $# -le 1 ]]; then
50-    $open_cmd "$url"
51-    return
52-  fi
53-  if [[ $1 == 'duckduckgo' ]]; then
54-  #slightly different search syntax for DDG
55-    url="${url}/?q="
56+  # search or go to main page depending on number of arguments passed
57+  if [[ $# -gt 1 ]]; then
58+    # build search url:
59+    # join arguments passed with '+', then append to search engine URL
60+    url="${urls[$1]}${(j:+:)@[2,-1]}"
61   else
62-    url="${url}/search?q="
63+    # build main page url:
64+    # split by '/', then rejoin protocol (1) and domain (2) parts with '//'
65+    url="${(j://:)${(s:/:)urls[$1]}[1,2]}"
66   fi
67-  shift   # shift out $1
68-
69-  while [[ $# -gt 0 ]]; do
70-    url="${url}$1+"
71-    shift
72-  done
73 
74-  url="${url%?}" # remove the last '+'
75-  nohup $open_cmd "$url" >/dev/null 2&>1
76+  nohup $open_cmd "$url" &>/dev/null
77 }
78 
79 
80@@ -45,6 +48,8 @@ alias bing='web_search bing'
81 alias google='web_search google'
82 alias yahoo='web_search yahoo'
83 alias ddg='web_search duckduckgo'
84+alias yandex='web_search yandex'
85+
86 #add your own !bang searches here
87 alias wiki='web_search duckduckgo \!w'
88 alias news='web_search duckduckgo \!n'