functions.zsh 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. setopt norematchpcre
  146. local -a opts
  147. zparseopts -D -E -a opts r m P
  148. local in_str="$@"
  149. local url_str=""
  150. local spaces_as_plus
  151. if [[ -z $opts[(r)-P] ]]; then spaces_as_plus=1; fi
  152. local str="$in_str"
  153. # URLs must use UTF-8 encoding; convert str to UTF-8 if required
  154. local encoding=$langinfo[CODESET]
  155. local safe_encodings
  156. safe_encodings=(UTF-8 utf8 US-ASCII)
  157. if [[ -z ${safe_encodings[(r)$encoding]} ]]; then
  158. str=$(echo -E "$str" | iconv -f $encoding -t UTF-8)
  159. if [[ $? != 0 ]]; then
  160. echo "Error converting string from $encoding to UTF-8" >&2
  161. return 1
  162. fi
  163. fi
  164. # Use LC_CTYPE=C to process text byte-by-byte
  165. # Note that this doesn't work in Termux, as it only has UTF-8 locale.
  166. # Characters will be processed as UTF-8, which is fine for URLs.
  167. local i byte ord LC_ALL=C
  168. export LC_ALL
  169. local reserved=';/?:@&=+$,'
  170. local mark='_.!~*''()-'
  171. local dont_escape="[A-Za-z0-9"
  172. if [[ -z $opts[(r)-r] ]]; then
  173. dont_escape+=$reserved
  174. fi
  175. # $mark must be last because of the "-"
  176. if [[ -z $opts[(r)-m] ]]; then
  177. dont_escape+=$mark
  178. fi
  179. dont_escape+="]"
  180. # Implemented to use a single printf call and avoid subshells in the loop,
  181. # for performance (primarily on Windows).
  182. local url_str=""
  183. for (( i = 1; i <= ${#str}; ++i )); do
  184. byte="$str[i]"
  185. if [[ "$byte" =~ "$dont_escape" ]]; then
  186. url_str+="$byte"
  187. else
  188. if [[ "$byte" == " " && -n $spaces_as_plus ]]; then
  189. url_str+="+"
  190. elif [[ "$PREFIX" = *com.termux* ]]; then
  191. # Termux does not have non-UTF8 locales, so just send the UTF-8 character directly
  192. url_str+="$byte"
  193. else
  194. ord=$(( [##16] #byte ))
  195. url_str+="%$ord"
  196. fi
  197. fi
  198. done
  199. echo -E "$url_str"
  200. }
  201. # URL-decode a string
  202. #
  203. # Decodes a RFC 2396 URL-encoded (%-escaped) string.
  204. # This decodes the '+' and '%' escapes in the input string, and leaves
  205. # other characters unchanged. Does not enforce that the input is a
  206. # valid URL-encoded string. This is a convenience to allow callers to
  207. # pass in a full URL or similar strings and decode them for human
  208. # presentation.
  209. #
  210. # Outputs the encoded string on stdout.
  211. # Returns nonzero if encoding failed.
  212. #
  213. # Usage:
  214. # omz_urldecode <urlstring> - prints decoded string followed by a newline
  215. function omz_urldecode {
  216. emulate -L zsh
  217. local encoded_url=$1
  218. # Work bytewise, since URLs escape UTF-8 octets
  219. local caller_encoding=$langinfo[CODESET]
  220. local LC_ALL=C
  221. export LC_ALL
  222. # Change + back to ' '
  223. local tmp=${encoded_url:gs/+/ /}
  224. # Protect other escapes to pass through the printf unchanged
  225. tmp=${tmp:gs/\\/\\\\/}
  226. # Handle %-escapes by turning them into `\xXX` printf escapes
  227. tmp=${tmp:gs/%/\\x/}
  228. local decoded="$(printf -- "$tmp")"
  229. # Now we have a UTF-8 encoded string in the variable. We need to re-encode
  230. # it if caller is in a non-UTF-8 locale.
  231. local -a safe_encodings
  232. safe_encodings=(UTF-8 utf8 US-ASCII)
  233. if [[ -z ${safe_encodings[(r)$caller_encoding]} ]]; then
  234. decoded=$(echo -E "$decoded" | iconv -f UTF-8 -t $caller_encoding)
  235. if [[ $? != 0 ]]; then
  236. echo "Error converting string from UTF-8 to $caller_encoding" >&2
  237. return 1
  238. fi
  239. fi
  240. echo -E "$decoded"
  241. }