functions.zsh 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. function zsh_stats() {
  2. fc -l 1 \
  3. | awk '{ CMD[$2]++; count++; } END { for (a in CMD) print CMD[a] " " CMD[a]*100/count "% " a }' \
  4. | grep -v "./" | sort -nr | head -n 20 | column -c3 -s " " -t | nl
  5. }
  6. function uninstall_oh_my_zsh() {
  7. command env ZSH="$ZSH" sh "$ZSH/tools/uninstall.sh"
  8. }
  9. function upgrade_oh_my_zsh() {
  10. echo >&2 "${fg[yellow]}Note: \`$0\` is deprecated. Use \`omz update\` instead.$reset_color"
  11. omz update
  12. }
  13. function open_command() {
  14. local open_cmd
  15. # define the open command
  16. case "$OSTYPE" in
  17. darwin*) open_cmd='open' ;;
  18. cygwin*) open_cmd='cygstart' ;;
  19. linux*) [[ "$(uname -r)" != *icrosoft* ]] && open_cmd='nohup xdg-open' || {
  20. open_cmd='cmd.exe /c start ""'
  21. [[ -e "$1" ]] && { 1="$(wslpath -w "${1:a}")" || return 1 }
  22. } ;;
  23. msys*) open_cmd='start ""' ;;
  24. *) echo "Platform $OSTYPE not supported"
  25. return 1
  26. ;;
  27. esac
  28. # If a URL is passed, $BROWSER might be set to a local browser within SSH.
  29. # See https://github.com/ohmyzsh/ohmyzsh/issues/11098
  30. if [[ -n "$BROWSER" && "$1" = (http|https)://* ]]; then
  31. "$BROWSER" "$@"
  32. return
  33. fi
  34. ${=open_cmd} "$@" &>/dev/null
  35. }
  36. # take functions
  37. # mkcd is equivalent to takedir
  38. function mkcd takedir() {
  39. mkdir -p $@ && cd ${@:$#}
  40. }
  41. function takeurl() {
  42. local data thedir
  43. data="$(mktemp)"
  44. curl -L "$1" > "$data"
  45. tar xf "$data"
  46. thedir="$(tar tf "$data" | head -n 1)"
  47. rm "$data"
  48. cd "$thedir"
  49. }
  50. function takegit() {
  51. git clone "$1"
  52. cd "$(basename ${1%%.git})"
  53. }
  54. function take() {
  55. if [[ $1 =~ ^(https?|ftp).*\.(tar\.(gz|bz2|xz)|tgz)$ ]]; then
  56. takeurl "$1"
  57. elif [[ $1 =~ ^([A-Za-z0-9]\+@|https?|git|ssh|ftps?|rsync).*\.git/?$ ]]; then
  58. takegit "$1"
  59. else
  60. takedir "$@"
  61. fi
  62. }
  63. #
  64. # Get the value of an alias.
  65. #
  66. # Arguments:
  67. # 1. alias - The alias to get its value from
  68. # STDOUT:
  69. # The value of alias $1 (if it has one).
  70. # Return value:
  71. # 0 if the alias was found,
  72. # 1 if it does not exist
  73. #
  74. function alias_value() {
  75. (( $+aliases[$1] )) && echo $aliases[$1]
  76. }
  77. #
  78. # Try to get the value of an alias,
  79. # otherwise return the input.
  80. #
  81. # Arguments:
  82. # 1. alias - The alias to get its value from
  83. # STDOUT:
  84. # The value of alias $1, or $1 if there is no alias $1.
  85. # Return value:
  86. # Always 0
  87. #
  88. function try_alias_value() {
  89. alias_value "$1" || echo "$1"
  90. }
  91. #
  92. # Set variable "$1" to default value "$2" if "$1" is not yet defined.
  93. #
  94. # Arguments:
  95. # 1. name - The variable to set
  96. # 2. val - The default value
  97. # Return value:
  98. # 0 if the variable exists, 3 if it was set
  99. #
  100. function default() {
  101. (( $+parameters[$1] )) && return 0
  102. typeset -g "$1"="$2" && return 3
  103. }
  104. #
  105. # Set environment variable "$1" to default value "$2" if "$1" is not yet defined.
  106. #
  107. # Arguments:
  108. # 1. name - The env variable to set
  109. # 2. val - The default value
  110. # Return value:
  111. # 0 if the env variable exists, 3 if it was set
  112. #
  113. function env_default() {
  114. [[ ${parameters[$1]} = *-export* ]] && return 0
  115. export "$1=$2" && return 3
  116. }
  117. # Required for $langinfo
  118. zmodload zsh/langinfo
  119. # URL-encode a string
  120. #
  121. # Encodes a string using RFC 2396 URL-encoding (%-escaped).
  122. # See: https://www.ietf.org/rfc/rfc2396.txt
  123. #
  124. # By default, reserved characters and unreserved "mark" characters are
  125. # not escaped by this function. This allows the common usage of passing
  126. # an entire URL in, and encoding just special characters in it, with
  127. # the expectation that reserved and mark characters are used appropriately.
  128. # The -r and -m options turn on escaping of the reserved and mark characters,
  129. # respectively, which allows arbitrary strings to be fully escaped for
  130. # embedding inside URLs, where reserved characters might be misinterpreted.
  131. #
  132. # Prints the encoded string on stdout.
  133. # Returns nonzero if encoding failed.
  134. #
  135. # Usage:
  136. # omz_urlencode [-r] [-m] [-P] <string> [<string> ...]
  137. #
  138. # -r causes reserved characters (;/?:@&=+$,) to be escaped
  139. #
  140. # -m causes "mark" characters (_.!~*''()-) to be escaped
  141. #
  142. # -P causes spaces to be encoded as '%20' instead of '+'
  143. function omz_urlencode() {
  144. emulate -L zsh
  145. local -a opts
  146. zparseopts -D -E -a opts r m P
  147. local in_str="$@"
  148. local url_str=""
  149. local spaces_as_plus
  150. if [[ -z $opts[(r)-P] ]]; then spaces_as_plus=1; fi
  151. local str="$in_str"
  152. # URLs must use UTF-8 encoding; convert str to UTF-8 if required
  153. local encoding=$langinfo[CODESET]
  154. local safe_encodings
  155. safe_encodings=(UTF-8 utf8 US-ASCII)
  156. if [[ -z ${safe_encodings[(r)$encoding]} ]]; then
  157. str=$(echo -E "$str" | iconv -f $encoding -t UTF-8)
  158. if [[ $? != 0 ]]; then
  159. echo "Error converting string from $encoding to UTF-8" >&2
  160. return 1
  161. fi
  162. fi
  163. # Use LC_CTYPE=C to process text byte-by-byte
  164. # Note that this doesn't work in Termux, as it only has UTF-8 locale.
  165. # Characters will be processed as UTF-8, which is fine for URLs.
  166. local i byte ord LC_ALL=C
  167. export LC_ALL
  168. local reserved=';/?:@&=+$,'
  169. local mark='_.!~*''()-'
  170. local dont_escape="[A-Za-z0-9"
  171. if [[ -z $opts[(r)-r] ]]; then
  172. dont_escape+=$reserved
  173. fi
  174. # $mark must be last because of the "-"
  175. if [[ -z $opts[(r)-m] ]]; then
  176. dont_escape+=$mark
  177. fi
  178. dont_escape+="]"
  179. # Implemented to use a single printf call and avoid subshells in the loop,
  180. # for performance (primarily on Windows).
  181. local url_str=""
  182. for (( i = 1; i <= ${#str}; ++i )); do
  183. byte="$str[i]"
  184. if [[ "$byte" =~ "$dont_escape" ]]; then
  185. url_str+="$byte"
  186. else
  187. if [[ "$byte" == " " && -n $spaces_as_plus ]]; then
  188. url_str+="+"
  189. elif [[ "$PREFIX" = *com.termux* ]]; then
  190. # Termux does not have non-UTF8 locales, so just send the UTF-8 character directly
  191. url_str+="$byte"
  192. else
  193. ord=$(( [##16] #byte ))
  194. url_str+="%$ord"
  195. fi
  196. fi
  197. done
  198. echo -E "$url_str"
  199. }
  200. # URL-decode a string
  201. #
  202. # Decodes a RFC 2396 URL-encoded (%-escaped) string.
  203. # This decodes the '+' and '%' escapes in the input string, and leaves
  204. # other characters unchanged. Does not enforce that the input is a
  205. # valid URL-encoded string. This is a convenience to allow callers to
  206. # pass in a full URL or similar strings and decode them for human
  207. # presentation.
  208. #
  209. # Outputs the encoded string on stdout.
  210. # Returns nonzero if encoding failed.
  211. #
  212. # Usage:
  213. # omz_urldecode <urlstring> - prints decoded string followed by a newline
  214. function omz_urldecode {
  215. emulate -L zsh
  216. local encoded_url=$1
  217. # Work bytewise, since URLs escape UTF-8 octets
  218. local caller_encoding=$langinfo[CODESET]
  219. local LC_ALL=C
  220. export LC_ALL
  221. # Change + back to ' '
  222. local tmp=${encoded_url:gs/+/ /}
  223. # Protect other escapes to pass through the printf unchanged
  224. tmp=${tmp:gs/\\/\\\\/}
  225. # Handle %-escapes by turning them into `\xXX` printf escapes
  226. tmp=${tmp:gs/%/\\x/}
  227. local decoded="$(printf -- "$tmp")"
  228. # Now we have a UTF-8 encoded string in the variable. We need to re-encode
  229. # it if caller is in a non-UTF-8 locale.
  230. local -a safe_encodings
  231. safe_encodings=(UTF-8 utf8 US-ASCII)
  232. if [[ -z ${safe_encodings[(r)$caller_encoding]} ]]; then
  233. decoded=$(echo -E "$decoded" | iconv -f UTF-8 -t $caller_encoding)
  234. if [[ $? != 0 ]]; then
  235. echo "Error converting string from UTF-8 to $caller_encoding" >&2
  236. return 1
  237. fi
  238. fi
  239. echo -E "$decoded"
  240. }