80d856e1655cc2b2e9d6899bae884631283a8063

Author
Marc Cornellà <marc.cornella@live.com>
Committer
Marc Cornellà <marc.cornella@live.com>
Date

Message

Clean up web-search plugin logic to allow easier changes

Diff

 1diff --git a/plugins/web-search/web-search.plugin.zsh b/plugins/web-search/web-search.plugin.zsh
 2index 28559deb9d084895371a348ee89585be703b0b33..1e661250ac3b6a3a293cad9c3ed8a3533d739c5a 100644
 3--- a/plugins/web-search/web-search.plugin.zsh
 4+++ b/plugins/web-search/web-search.plugin.zsh
 5@@ -1,42 +1,43 @@
 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://www.yahoo.com/search?q="
24+    duckduckgo  "https://www.duckduckgo.com/?q="
25+  )
26+
27+  # define the open command
28+  case "$OSTYPE" in
29+    darwin*)  open_cmd="open" ;;
30+    linux*)   open_cmd="xdg-open" ;;
31+    *)        echo "Platform $OSTYPE not supported"
32+              return 1
33+              ;;
34+  esac
35 
36   # check whether the search engine is supported
37-  if [[ ! $1 =~ '(google|bing|yahoo|duckduckgo)' ]];
38-  then
39+  if [[ -z "$urls[$1]" ]]; then
40     echo "Search engine $1 not supported."
41     return 1
42   fi
43 
44-  local url="http://www.$1.com"
45-
46-  # no keyword provided, simply open the search engine homepage
47-  if [[ $# -le 1 ]]; then
48-    $open_cmd "$url"
49-    return
50-  fi
51-  if [[ $1 == 'duckduckgo' ]]; then
52-  #slightly different search syntax for DDG
53-    url="${url}/?q="
54+  # search or go to main page depending on number of arguments passed
55+  if [[ $# -gt 1 ]]; then
56+    # build search url:
57+    # join arguments passed with '+', then append to search engine URL
58+    url="${urls[$1]}${(j:+:)@[2,-1]}"
59   else
60-    url="${url}/search?q="
61+    # build main page url:
62+    # split by '/', then rejoin protocol (1) and domain (2) parts with '//'
63+    url="${(j://:)${(s:/:)urls[$1]}[1,2]}"
64   fi
65-  shift   # shift out $1
66-
67-  while [[ $# -gt 0 ]]; do
68-    url="${url}$1+"
69-    shift
70-  done
71 
72-  url="${url%?}" # remove the last '+'
73   nohup $open_cmd "$url" >/dev/null 2&>1
74 }
75