You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1407 lines
33 KiB

  1. #!/bin/sh
  2. # TODO: decide the naming scheme of variables (global, local, ...)
  3. expr "$-" : '^.*i' >/dev/null || return
  4. ##########################################
  5. __shrc_lock=/tmp/shrc_lock.$USER.$$
  6. test -f "$__shrc_lock" && return
  7. touch "$__shrc_lock"
  8. ##########################################
  9. null(){
  10. "$@" >/dev/null 2>&1
  11. }
  12. __safe_run(){
  13. type $1 >/dev/null 2>&1 && "$@"
  14. }
  15. __match(){
  16. # __match str word
  17. # return 0 if word is found in str
  18. expr "$1" : ".*$2.*" >/dev/null
  19. }
  20. #################################
  21. # profile-like setups
  22. __safe_add_path_r(){
  23. # add path to right
  24. test -d "$1" && PATH="${PATH}:$1"
  25. }
  26. __safe_add_path_l(){
  27. # add path to left
  28. test -d "$1" && PATH="$1:${PATH}"
  29. }
  30. __safe_add_path_l "$HOME/.cabal/bin"
  31. __safe_add_path_l "$HOME/.local/lib/gems/bin"
  32. __safe_add_path_l "$HOME/.local/bin"
  33. __safe_add_path_l "$HOME/.gem/ruby/2.1.0/bin"
  34. __safe_add_path_r "/c/mingw/bin"
  35. __safe_add_path_r "/c/mingw/msys/1.0/bin"
  36. # macports coreutils
  37. # $isdarwin cannot be used it is not defined yet
  38. __safe_add_path_l "/opt/local/bin"
  39. __safe_add_path_l "/opt/local/sbin"
  40. __safe_add_path_l "/opt/local/libexec/gnubin"
  41. __safe_add_path_l \
  42. "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/bin"
  43. test -f "${__dotdir}/rc.py" && export PYTHONSTARTUP="${__dotdir}/rc.py"
  44. test -d "$HOME/.local/lib/python/site-packages" && \
  45. export PYTHONPATH="${PYTHONPATH}:${HOME}/.local/lib/python/site-packages"
  46. export GEM_HOME="$HOME/.local/lib/gems"
  47. export RUBYLIB="$RUBYLIB:$HOME/.local/lib/gems/lib"
  48. # it is not so good
  49. # http://archive.linux.or.jp/JF/JFdocs/Program-Library-HOWTO/shared-libraries.html
  50. # http://superuser.com/questions/324613/installing-a-library-locally-in-home-directory-but-program-doesnt-recognize-it
  51. # without this ENV i cannot run tmux. another way is to use --disable-shared
  52. # when building tmux
  53. if ! __match "$LD_LIBRARY_PATH" "$HOME/.local/lib"
  54. then
  55. export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$HOME/.local/lib"
  56. fi
  57. # in my environment powerdown does not work
  58. test -z "$DISPLAY" && test -z "$SSH_CONNECTION" && \
  59. type setterm >/dev/null 2>&1 && \
  60. setterm -blank 30 -powersave on # -powerdown 10
  61. #########################
  62. # shrc.common
  63. # this variable must consistent with setup.sh
  64. __shrc_common="$HOME/.shrc.common"
  65. if test -f "$__shrc_common"
  66. then
  67. . "$__shrc_common"
  68. else
  69. echo "$__shrc_common not found."
  70. echo "Run setup.sh first."
  71. return
  72. fi
  73. ##########################
  74. # system type
  75. gnu_coreutils=false # for mac
  76. null ls --version && gnu_coreutils=true
  77. inbash=false
  78. inzsh=false
  79. if test -n "$BASH_VERSION"
  80. then
  81. inbash=true
  82. elif test -n "$ZSH_VERSION"
  83. then
  84. inzsh=true
  85. fi
  86. #################################
  87. # file pathes:
  88. # shrc: Path to this file
  89. if $inbash
  90. then
  91. __shrc="$BASH_SOURCE"
  92. elif $inzsh
  93. then
  94. __shrc="$0"
  95. fi
  96. ##################################
  97. # EnvVal definitions
  98. test "$TERM" = linux && export LANG=C
  99. export LC_MESSAGES=C
  100. export LC_TIME=C
  101. export TERMCAP="${TERMCAP}:vb="
  102. $ismsys && export HOSTNAME
  103. # export ENV=~/.shrc
  104. if false $iswindows
  105. then
  106. export PAGER='tr -d \\r | less'
  107. else
  108. export PAGER="less"
  109. fi
  110. export LESS="-iRMX"
  111. # Style for lesspipe is defined in esc.style
  112. _src_hilite_lp_path="`command -v src-hilite-lesspipe.sh 2>/dev/null`"
  113. for f in /usr/share/source-highlight/src-hilite-lesspipe.sh
  114. do
  115. test -z "$_src_hilite_lp_path" && test -e "$f" && _src_hilite_lp_path="$f"
  116. done
  117. test -n "$_src_hilite_lp_path" && export LESSOPEN="| $_src_hilite_lp_path %s"
  118. if null type vim
  119. then
  120. export EDITOR=vim
  121. else
  122. export EDITOR=vi
  123. fi
  124. # export CDPATH=".:~"
  125. export VISUAL="$EDITOR"
  126. export GIT_PAGER="less -F"
  127. export GIT_EDITOR="$EDITOR"
  128. export GIT_MERGE_AUTOEDIT=no
  129. if test -n "$TMUX" && \
  130. __match $TERM screen && \
  131. __match `tmux display -p '#{client_termname}'` 256color
  132. then
  133. TERM=screen-256color
  134. fi
  135. # set TMP, TEMP, TMPDIR
  136. if test -z "$TMP"
  137. then
  138. if test -n "$TMPDIR"
  139. then
  140. export TMP=$TMPDIR
  141. elif test -n "$TEMP"
  142. then
  143. export TMP="$TEMP"
  144. else
  145. export TMP=/tmp
  146. fi
  147. fi
  148. __match "$TMP" "${USER}-tmp" >/dev/null || TMP="${TMP}/${USER}-tmp"
  149. test -d "$TMP" || mkdir -p "$TMP"
  150. export TEMP=$TMP
  151. export TMPDIR=$TMP
  152. if ! $iswindows && null type stty
  153. then
  154. stty stop undef # unbind C-s to stop displaying output
  155. # stty erase '^h'
  156. fi
  157. if $iswindows
  158. then
  159. export USER=$USERNAME
  160. fi
  161. if test -d ~/dbx
  162. then
  163. export CHIT_PATH="$HOME/dbx/.chit"
  164. fi
  165. # adhoc fix for ansible on cygwin
  166. # http://blog.s-uni.net/2013/08/27/ansible-running-on-cygwin/
  167. if $incygwin
  168. then
  169. export ANSIBLE_SSH_ARGS="-o ControlMaster=no"
  170. fi
  171. ##########################
  172. # Zsh specific preferences
  173. # http://www.clear-code.com/blog/2011/9/5.html
  174. if $inzsh
  175. then
  176. bindkey -e
  177. # http://zsh.sourceforge.net/Guide/zshguide06.html#l147
  178. autoload compinit; compinit
  179. # supress cycle by tab
  180. unsetopt auto_menu
  181. # unsetopt correct
  182. setopt complete_aliases
  183. setopt auto_list
  184. setopt bash_auto_list
  185. setopt magic_equal_subst
  186. setopt list_types
  187. # what is the difference of these two?
  188. setopt auto_param_slash
  189. setopt mark_dirs
  190. zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
  191. zstyle ':completion:*' format '%B%d%b'
  192. zstyle ':completion:*' group-name ''
  193. zstyle ':completion:*' use-cache yes
  194. # zstyle ':completion:*:cd:*' tag-order local-directories
  195. zstyle ':completion:*' completer _complete _bash_completions \
  196. _history
  197. # zstyle ':completion:*:*:cd:*' completer
  198. zstyle ':completion:*' accept-exact-dirs true
  199. zstyle ':completion:*' special-dirs true
  200. autoload colors; colors
  201. # autoload -Uz promptinit
  202. # promptinit
  203. # prompt walters
  204. setopt hist_ignore_dups
  205. setopt hist_ignore_all_dups
  206. setopt hist_save_no_dups
  207. setopt extended_history
  208. setopt share_history
  209. setopt append_history
  210. HISTFILE=$HOME/.zsh-history
  211. HISTSIZE=100000
  212. SAVEHIST=100000
  213. setopt prompt_subst
  214. setopt interactive_comments
  215. fi
  216. ######################
  217. # Print welcome messages
  218. command -v fortune >/dev/null && {
  219. if command -v cowsay >/dev/null
  220. then
  221. fortune | cowsay
  222. echo
  223. fortune -o | cowsay
  224. echo
  225. else
  226. fortune
  227. echo
  228. fortune -o
  229. echo
  230. fi
  231. }
  232. uname -a
  233. $iswindows && alias tty="echo cmd.exe"
  234. echo TERM $TERM with $(tput colors) colors using $(tty)
  235. echo
  236. __safe_run w yuk
  237. # if null type tmux
  238. # then
  239. # echo
  240. # echo tmux sessions:
  241. # tmux ls 2>/dev/null| sed -e 's/^/ /g'
  242. # echo
  243. # fi
  244. # if test -n "$TMUX"
  245. # then
  246. # tmux display -p \
  247. # 'TMUX #S:#I:#W.#P, client TERM: #{client_termname}' \
  248. # 2>/dev/null
  249. # echo
  250. # fi
  251. ###################################
  252. # some aliases and functions
  253. # __func_name: never used interactively
  254. # _func_name: usually not used interactively
  255. __safe_alias(){
  256. # __safe_alias <name>=<command>
  257. _bin=`expr "$1" : '^[^=]*=\([^ ]*\)'`
  258. test -n "$_bin" && \
  259. null type $_bin && \
  260. alias "$1"
  261. }
  262. $gnu_coreutils && _timeoption=" --time-style=long-iso"
  263. # color prefs
  264. if $gnu_coreutils
  265. then
  266. # http://qiita.com/yuyuchu3333/items/84fa4e051c3325098be3
  267. # gnu coreutils LS_COLORS is used
  268. null type dircolors && eval `dircolors`
  269. _coloroption=" --color=auto"
  270. else
  271. # export LSCOLORS=gxfxcxdxbxegedabagacad
  272. export LSCOLORS=DxGxcxdxCxegedabagacad
  273. export CLICOLOR=1
  274. fi
  275. alias ls="ls -hCF${_coloroption}${_timeoption}"
  276. _timeformat_iso="%Y-%m-%dT%H:%M:%S%z"
  277. _timeformat_rfc2822="%a, %d %b %Y %T %z"
  278. _timeformat_num="%Y%m%d%H%M%S"
  279. alias datenum="date +$_timeformat_num"
  280. # export GREP_OPTIONS=""
  281. alias gr="grep -n --color=always"
  282. $iswindows && alias gr="grep -n"
  283. alias less="less -F"
  284. __safe_alias em="emacs -nw"
  285. __safe_alias vi=vim
  286. alias pstree="LANG=C pstree"
  287. alias cp="cp -v"
  288. alias mv="mv -v"
  289. alias rm="rm -v"
  290. alias mkdir="mkdir -v"
  291. alias rmdir="rmdir -v"
  292. alias psaux="ps auxww"
  293. alias modest="ionice -c 2 -n 7 nice -n 19"
  294. alias q=exit
  295. __safe_alias e3=e3em
  296. #alias dirs="dirs -v -l | \grep -v \$(printf '%s$' \$PWD)"
  297. alias po=popd
  298. alias pu=pushd
  299. __safe_alias sudo="sudo " # use aliases through sudo
  300. __safe_alias sudoe="sudoedit"
  301. # __safe_alias halt="sudo halt"
  302. # __safe_alias reboot="sudo reboot"
  303. null type dbus-send && {
  304. alias suspend="dbus-send --system --print-reply \
  305. --dest=org.freedesktop.UPower \
  306. /org/freedesktop/UPower org.freedesktop.UPower.Suspend"
  307. alias hibernate="dbus-send --system --print-reply \
  308. --dest=org.freedesktop.UPower \
  309. /org/freedesktop/UPower org.freedesktop.UPower.Hibernate"
  310. }
  311. alias rand="echo \$RANDOM"
  312. __safe_alias xunp="file-roller -h"
  313. __safe_alias pc="sudo \paco -D"
  314. alias pycalc="python -i -c 'from math import *' "
  315. __safe_alias py3=python3
  316. __safe_alias py2=python2
  317. __safe_alias ipy=ipython
  318. __safe_alias ipy3=ipython3
  319. __safe_alias ipy2=ipython2
  320. # Sometimes SHELL cannot be used. For example, when running bash inside zsh
  321. # SHELL is set to be /bin/zsh
  322. if $inbash
  323. then
  324. alias _reloadrc="rm '$__shrc_lock'; exec bash"
  325. elif $inzsh
  326. then
  327. alias _reloadrc="rm '$__shrc_lock'; exec zsh"
  328. else
  329. alias _reloadrc="rm '$__shrc_lock'; exec $SHELL"
  330. fi
  331. # alias mytime="date +%Y%m%d-%H%M%S"
  332. alias sh="ENV=$HOME/.shrc PS1=\$\ PROMPT_COMMAND="" sh"
  333. # some extra utilities
  334. # type trash >/dev/null 2>&1 && alias rm=trash
  335. __safe_alias mpg123="mpg123 -C -v --title"
  336. __safe_alias xm="xmms2"
  337. #export PLAYER="mpg123 -C -v --title"
  338. __safe_alias screen="screen -e^z^z"
  339. #alias zcd="cd \`zenity --file-selection --directory\`"
  340. __safe_alias gtags="gtags --verbose"
  341. __safe_alias htags="htags --xhtml --symbol --line-number \
  342. --frame --alphabet --verbose"
  343. __safe_alias au=aunpack
  344. # __safe_alias lv="lv|less"
  345. __safe_alias rs="rsync --progress --itemize-changes --compress"
  346. __safe_alias vagr=vagrant
  347. __safe_alias ztw='twitter set "`zenity --entry --title ztw --text Status:`"'
  348. if $iscygwin
  349. then
  350. __my_wget_options=" --no-check-certificate"
  351. __safe_alias wget="wget $__my_wget_options"
  352. fi
  353. if $isdarwin
  354. then
  355. alias updatedb="LC_ALL=C updatedb"
  356. # do not use locate installed by macports
  357. test -x /usr/bin/locate && alias locate="/usr/bin/locate"
  358. fi
  359. # somehow not work
  360. # typeset -ga chpwd_functions
  361. # chpwd_functions+=pwd
  362. # chpwd(){
  363. # pwd
  364. # }
  365. cd(){
  366. builtin cd "$@" && pwd
  367. }
  368. root(){
  369. if test "`git rev-parse --is-inside-work-tree 2>/dev/null`" = true
  370. then
  371. cd "`git rev-parse --show-toplevel`"
  372. else
  373. cd /
  374. fi
  375. }
  376. # pad
  377. alias pad=notepad
  378. __safe_alias pad=gedit
  379. __safe_alias pad=leafpad
  380. $isdarwin && alias pad="open -e"
  381. __find_latest_vimdir(){
  382. vimdir=/usr/share/vim
  383. if test -d "$vimdir"
  384. then
  385. find "$vimdir" -name 'vim??' -type d | sort | tail -n 1
  386. else
  387. echo ""
  388. fi
  389. }
  390. for f in /usr/share/vim/vimcurrent "`__find_latest_vimdir`"
  391. do
  392. test -n "$f" || continue
  393. f="$f/macros/less.sh"
  394. test -f $f && alias vl=$f && break
  395. done
  396. __safe_alias pa="pacman --color=always"
  397. __safe_alias pa="pacmatic --color=always"
  398. __safe_alias pa="pacapt"
  399. __safe_alias yt=yaourt
  400. # variable for yaourt
  401. null type pacmatic && export PACMAN="pacmatic"
  402. __safe_alias cower="cower --color=auto"
  403. __my_pacman_update_mirrorlist_with_reflector(){
  404. f=/etc/pacman.d/mirrorlist
  405. cmd="$(expr "$(grep -m 1 reflector $f)" : '# With: *\(.*\)')"
  406. if test -z "$cmd"
  407. then
  408. cmd="reflector --verbose --number 5 --sort rate --protocol http --protocol https --save $f"
  409. fi
  410. echo ">>> $cmd ..." 1>&2
  411. sudo sh -c "$cmd" && cat $f
  412. }
  413. null type reflector && test -d /etc/pacman.d && \
  414. alias reflect_mirrorlist=__my_pacman_update_mirrorlist_with_reflector
  415. null type apt-get && {
  416. alias aupgrade="sudo sh -xc 'apt-get autoremove --yes && \
  417. apt-get update --yes && apt-get upgrade --yes'"
  418. alias aptin="apt-get install"
  419. alias aptsearch="apt-cache search"
  420. alias aptshow="apt-cache show"
  421. }
  422. null type port && {
  423. alias port="port -v"
  424. alias pupgrade="sudo sh -xc 'port -v selfupdate && \
  425. port -v upgrade outdated'"
  426. }
  427. if $iscygwin
  428. then
  429. null type windate || \
  430. alias windate="cmd.exe //c 'echo %DATE%-%TIME%'"
  431. # alias cygsu="cygstart /cygwinsetup.exe"
  432. fi
  433. mkpatch(){
  434. if test $# -eq 0
  435. then
  436. echo "usage: mkpatch <olddir> <newdir>"
  437. elif ! test -d "$1"
  438. then
  439. echo "mkpatch: $1 is not a directory"
  440. elif ! test -d "$2"
  441. then
  442. echo "mkpatch: $2 is not a directory"
  443. else
  444. diff -Naur "$1" "$2"
  445. fi
  446. }
  447. __sdcv_less(){
  448. command sdcv -n "$@" | less --quit-if-one-screen
  449. }
  450. command -v sdcv >/dev/null && alias dict=__sdcv_less
  451. g(){
  452. if test $# -eq 0 && null type git-info
  453. then
  454. git info
  455. else
  456. git -c color.ui=always "$@"
  457. fi
  458. }
  459. if null type _git && $inbash
  460. then
  461. # enable programmable completion for g
  462. complete -o bashdefault -o default -o nospace -F _git g 2>/dev/null \
  463. || complete -o default -o nospace -F _git g
  464. fi
  465. #git svn --help >/dev/null 2>&1 && alias gsvn="git svn"
  466. __safe_alias m=gitmemo
  467. alias setup.py3="sudo python3 setup.py install --record files.txt"
  468. randomstr(){
  469. len=$1
  470. test -z "$len" && len=8
  471. uuidgen | tr -d - | cut -c 1-len
  472. }
  473. datestr(){
  474. # datestr YYYYMMDDhhmmss
  475. if test -z "$1" || test "$1" = "-h"
  476. then
  477. echo "datestr: usage: datestr <YYYYMMDDhhmmss>"
  478. return 1
  479. fi
  480. dfmt="" # actual format for date command
  481. while test -n "$1"
  482. do
  483. fmt="$1"
  484. shift
  485. while test -n "$fmt"
  486. do
  487. case "$fmt" in
  488. YYYY*|yyyy*) # year
  489. dfmt="${dfmt}%Y"
  490. fmt="`echo "$fmt" | cut -c 5-`"
  491. ;;
  492. YY*|yy*) # last two digits of year
  493. dfmt="${dfmt}%y"
  494. fmt="`echo "$fmt" | cut -c 3-`"
  495. ;;
  496. MM*) # month (01..12)
  497. dfmt="${dfmt}%m"
  498. fmt="`echo "$fmt" | cut -c 3-`"
  499. ;;
  500. DD*|dd*) # day of month (01..12)
  501. dfmt="${dfmt}%d"
  502. fmt="`echo "$fmt" | cut -c 3-`"
  503. ;;
  504. HH* | hh*) # hour (00..23)
  505. dfmt="${dfmt}%H"
  506. fmt="`echo "$fmt" | cut -c 3-`"
  507. ;;
  508. mm*) # minute (00..59)
  509. dfmt="${dfmt}%M"
  510. fmt="`echo "$fmt" | cut -c 3-`"
  511. ;;
  512. SS*|ss*) # second (00..60)
  513. dfmt="${dfmt}%S"
  514. fmt="`echo "$fmt" | cut -c 3-`"
  515. ;;
  516. *)
  517. char=`echo "$fmt" | cut -c 1`
  518. dfmt="${dfmt}${char}"
  519. fmt="`echo "$fmt" | cut -c 2-`"
  520. ;;
  521. esac
  522. done
  523. done
  524. date +"$dfmt"
  525. }
  526. # ssh(){
  527. # # __my_terminal_title ssh
  528. # command ssh "$@"
  529. # }
  530. __ssh_with_cd(){
  531. # __ssh_with_cd <host> <directory> [<arg> ...]
  532. if test -z "$2"
  533. then
  534. echo "usage: __ssh_with_cd <host> <directory> [<arg> ...]"
  535. return 1
  536. fi
  537. host="$1"
  538. shift
  539. dir="$1"
  540. shift
  541. ssh "$host" "$@" -t "cd \"$dir\"; \$SHELL -l"
  542. }
  543. memo(){
  544. if test -z "$1"
  545. then
  546. _memo="memo.txt"
  547. else
  548. _memo="$1/memo.txt"
  549. fi
  550. $EDITOR "$_memo"
  551. if test -z "`cat "$_memo"`"
  552. then
  553. echo "$_memo is empty. Removing."
  554. rm "$_memo"
  555. fi
  556. }
  557. now(){
  558. ___tformat="%Y/%m/%d %H:%M:%S %z"
  559. cal
  560. REPLY=
  561. printf "\\r`date "+${___tformat}"`"
  562. read -t 1
  563. while test $? -ne 0
  564. do
  565. printf "\\r`date "+${___tformat}"`"
  566. read -t 1
  567. done
  568. }
  569. s(){
  570. if git rev-parse --git-dir >/dev/null 2>&1
  571. then
  572. echo ">> git grep -n $@" 1>&2
  573. git grep -n "$@"
  574. elif which ag >/dev/null 2>&1
  575. then
  576. echo ">> ag --pager=\"$PAGER\" $@" 1>&2
  577. ag --pager="$PAGER" "$@"
  578. elif which ack >/dev/null 2>&1
  579. then
  580. echo ">> ack --pager=\"$PAGER\" $@" 1>&2
  581. ack --pager="$PAGER" "$@"
  582. else
  583. echo \
  584. ">> find . " \
  585. "-path '*/.git' -prune -o" \
  586. "-path '*/.svn' -prune -o" \
  587. "-type f -exec grep -nH -e --color=always $@ {} +" 1>&2
  588. if test $# -eq 0
  589. then
  590. echo "No search word given." 1>&2
  591. return 1
  592. fi
  593. find . \
  594. -path '*/.git' -prune -o \
  595. -path '*/.svn' -prune -o \
  596. -type -f -exec grep -nH -e --color=always "$@" {} + \
  597. | $PAGER
  598. fi
  599. }
  600. MYMANPATH='/usr/lib/erlang/man'
  601. if $inbash || $inzsh
  602. then
  603. man(){
  604. env \
  605. LESS_TERMCAP_mb=$(printf "\e[1;35m") \
  606. LESS_TERMCAP_md=$(printf "\e[1;31m") \
  607. LESS_TERMCAP_me=$(printf "\e[0m") \
  608. LESS_TERMCAP_se=$(printf "\e[0m") \
  609. LESS_TERMCAP_so=$(printf "\e[1;44;33m") \
  610. LESS_TERMCAP_ue=$(printf "\e[0m") \
  611. LESS_TERMCAP_us=$(printf "\e[1;32m") \
  612. MANPATH="`manpath`:$MYMANPATH" \
  613. man "$@"
  614. }
  615. fi
  616. netwait(){
  617. while ! ping -c 1 -t 1 example.com
  618. do
  619. true
  620. done
  621. echo network works.
  622. }
  623. __realpath(){
  624. if type realpath >/dev/null 2>&1
  625. then
  626. command realpath "$@"
  627. else
  628. while ! test -d $1
  629. do
  630. shift
  631. done
  632. (command cd "$d" && echo "$PWD")
  633. # local d="$OLDPWD"
  634. # command cd "$1"
  635. # echo "$PWD"
  636. # command cd "$d"
  637. fi
  638. }
  639. __safe_alias tmux='env -u SHLVL tmux'
  640. tx(){
  641. tmux start-server
  642. if test -z "$1"
  643. then
  644. echo "usage: tx <session_name>"
  645. tmux list-sessions
  646. elif test -z "$TMUX"
  647. then
  648. # -A: attach if already exists
  649. # tmux new-session -A -c "$HOME" -s "$1"
  650. tmux new-session -A -s "$1"
  651. else
  652. # create new session if not exists yet
  653. # tmux has-session -t "$1" || TMUX= tmux new-session -d -c "$HOME" -s "$1"
  654. tmux has-session -t "$1" || TMUX= tmux new-session -d -s "$1"
  655. tmux switch-client -t "$1"
  656. fi
  657. }
  658. dt(){
  659. # dt [-h] [<name>] [<command ...>]
  660. __dtach_dir="${TMP}/dtach"
  661. mkdir -p "${__dtach_dir}"
  662. if test -n "${__MY_DTACH}"
  663. then
  664. # if already in dtach session print current session
  665. soc_name="`basename "$__MY_DTACH"`"
  666. echo "Current session: ${soc_name}"
  667. fi
  668. if test -z "$1"
  669. then
  670. # if no arg given show list of sessions
  671. echo "Sessions:"
  672. ls "${__dtach_dir}"
  673. return 0
  674. elif test "$1" = "-h"
  675. then
  676. echo "dt: usage: dt [-h] [<name>] [<command ...>]" 1>&2
  677. return 1
  678. fi
  679. # set socket name
  680. soc_name="${__dtach_dir}/$1"
  681. shift
  682. if test -n "$__MY_DTACH"
  683. then
  684. echo "dtach session cannot be nested." 1>&2
  685. return 1
  686. elif test -S "$soc_name"
  687. then
  688. dtach -a "$soc_name" -e ^^
  689. elif test -e "$soc_name"
  690. then
  691. echo "dt: File named $soc_name already exists."
  692. return 1
  693. elif test -z "$1"
  694. then
  695. # if no command given invoke current shell
  696. __MY_DTACH="$soc_name" dtach -c "$soc_name" -e ^^ sh -c "$SHELL"
  697. # echo "dt: Socket named $soc_name not exists and no command specified."
  698. # return 1
  699. else
  700. __MY_DTACH="$soc_name" dtach -c "$soc_name" -e ^^ "$@"
  701. fi
  702. }
  703. scr(){
  704. test -n "$1" && pf="${1}-"
  705. ___tformat="%Y%m%d-%H%M%S%z"
  706. ___file="${HOME}/${pf}`date +${___tformat}`.script"
  707. __MY_SCRIPT=${___file} script ${___file} "$@"
  708. }
  709. dtscr(){
  710. # dtscr <command ...>
  711. if test -z "$1"
  712. then
  713. echo "dtscr: usage: dtscr <command ...>"
  714. return 1
  715. fi
  716. ___cmdstr="`echo $@ | tr ' ' +`"
  717. ___tformat="%Y%m%d-%H%M%S%z"
  718. ___name="${pf}`date +${___tformat}`-${___cmdstr}"
  719. ___scr_file="${HOME}/${___name}.script"
  720. ___dt_dir="${TMP}/dtscr"
  721. mkdir -p "$___dt_dir"
  722. dtach -n "${___dt_dir}/${___name}" script "${___scr_file_}" "$@"
  723. # echo $_name
  724. # echo $_file
  725. }
  726. mcrypt_stream(){
  727. test $# -eq 2 || return 1
  728. case $1 in
  729. en)
  730. mcrypt --key $2 | base64 ;;
  731. de)
  732. base64 -d | mcrypt -d --key $2 ;;
  733. esac
  734. }
  735. gpg_stream(){
  736. test $# -eq 2 || return 1
  737. case $1 in
  738. en)
  739. gpg --passphrase $2 -c --batch |base64 ;;
  740. de)
  741. base64 -d|gpg --passphrase $2 -d --batch ;;
  742. esac
  743. }
  744. dgpg(){
  745. if test "$1" = help || test -z "$2"
  746. then
  747. echo "dgpg: dgpg <en|de> <src-suffix> [<dst-suffix>]" 1>&2
  748. return
  749. fi
  750. ___srcs="$2"
  751. ___dsts="$3"
  752. test -z "$___dsts" && ___dsts="${___srcs}.out"
  753. ___pw=
  754. echo -n "dgpg pw: "
  755. read -s ___pw
  756. echo ""
  757. test -z "$___pw" && return 1
  758. for f in *${___srcs}
  759. do
  760. ___d="$(basename "$f" "${___srcs}")${___dsts}"
  761. echo -n "Processing $f to $___d..."
  762. if test -d "$f"
  763. then
  764. echo "`printf 'failed (%s is directory)' $f`"
  765. elif test -f "$___d"
  766. then
  767. echo "`printf 'failed (%s is already exists)' $___d`"
  768. elif <"$f" gpg_stream $1 $___pw >"$___d" 2>/dev/null
  769. then
  770. echo "done"
  771. else
  772. echo "failed"
  773. test -f "$___d" && rm "$___d"
  774. fi
  775. done
  776. }
  777. alias enst="gpg_stream en"
  778. alias dest="gpg_stream de"
  779. showinfo(){
  780. echo "Japanese letters are 表示可能"
  781. __safe_run diskinfo
  782. ! $isdarwin && test -n "${DISPLAY}" && {
  783. __safe_run xrandr | \grep --color=never ^Screen
  784. }
  785. $iswindows || __safe_run finger $USER
  786. LANG=C __safe_runc id
  787. __safe_run xset q
  788. }
  789. x(){
  790. if [[ -z $DISPLAY ]] && ! [[ -e /tmp/.X11-unix/X0 ]] && (( EUID )); then
  791. #mkdir -p ~/.var/log
  792. # nohup startx >~/.var/log/xorg.log 2>&1 &
  793. # exit
  794. exec startx
  795. else
  796. echo "X cant be started! Another X is already running?" 1>&2
  797. fi
  798. }
  799. bak(){
  800. for file in "$@"
  801. do
  802. cp -v ${file} ${file}.bak
  803. done
  804. }
  805. di(){
  806. if type colordiff >/dev/null 2>&1 && test $TERM != dumb
  807. then
  808. ___diffcmd=colordiff
  809. else
  810. ___diffcmd=diff
  811. fi
  812. ${___diffcmd} -u "$@" | ${PAGER}
  813. }
  814. tb(){
  815. __datenum=`date +%Y%m%d-%H%M%S`
  816. __tb="$HOME/.var/tb/$__datenum"
  817. mkdir -p "$__tb"
  818. mv "$@" "$__tb"
  819. }
  820. mkdd(){
  821. _d=`date +%Y%m%d-%H%M%S` && \
  822. mkdir -p "$_d"
  823. }
  824. mkcd(){
  825. if test -z "$1"
  826. then
  827. echo "mkcd: usage: mkcd <dir>"
  828. return 1
  829. elif test -d "$1"
  830. then
  831. echo "Dir \"$1\" already exists."
  832. else
  833. mkdir -p "$1"
  834. echo "Dir \"$1\" created."
  835. fi
  836. cd "$1"
  837. }
  838. mkcdd(){
  839. # make and change date directory
  840. _d=`date +%Y%m%d-%H%M%S` && \
  841. mkcd "$_d"
  842. }
  843. if test -n "$TMUX" && null type reattach-to-user-namespace
  844. then
  845. alias pbpaste="reattach-to-user-namespace pbpaste"
  846. alias pbcopy="reattach-to-user-namespace pbcopy"
  847. fi
  848. catclip(){
  849. if $iswindows
  850. then
  851. cat /dev/clipboard | tr -d \\r
  852. elif $isdarwin
  853. then
  854. pbpaste
  855. else
  856. xclip -o -selection "clipboard"
  857. fi
  858. }
  859. setclip(){
  860. if test $# -eq 0
  861. then
  862. exec 3<&0
  863. else
  864. exec 3<<__EOF__
  865. `cat "$@"`
  866. __EOF__
  867. fi
  868. if $iswindows
  869. then
  870. 0<&3 sed -e 's/$/\r/' | tee /dev/clipboard
  871. elif $isdarwin
  872. then
  873. pbcopy 0<&3
  874. else
  875. 0<&3 xclip -i -f -selection "primary" | \
  876. xclip -i -f -selection "clipboard"
  877. fi
  878. exec 3<&-
  879. }
  880. open_file(){
  881. if $iscygwin
  882. then
  883. cygstart "$@"
  884. elif $ismsys
  885. then
  886. cmd.exe //c start "" "$@"
  887. elif $isdarwin
  888. then
  889. touch "$@"
  890. open "$@"
  891. elif $islinux
  892. then
  893. touch "$@"
  894. if null type pcmanfm; then
  895. LC_MESSAGES= pcmanfm "$@"
  896. else
  897. LC_MESSAGES= xdg-open "$@" &
  898. fi
  899. else
  900. cat "$@"
  901. fi
  902. }
  903. o(){
  904. if test $# -eq 0
  905. then
  906. open_file .
  907. else
  908. for f in "$@"
  909. do
  910. open_file "$(realpath "$f")"
  911. done
  912. fi
  913. }
  914. convmv_sjis2utf8_test(){
  915. convmv -r -f sjis -t utf8 *
  916. }
  917. convmv_sjis2utf8_notest(){
  918. convmv -r -f sjis -t utf8 * --notest
  919. }
  920. #################################################
  921. ## pastebin services
  922. ## https://wiki.archlinux.org/index.php/List_of_Applications/Internet#Pastebin_clients
  923. sprunge(){
  924. # http://sprunge.us
  925. if test -z "$1"
  926. then
  927. curl -F 'sprunge=<-' http://sprunge.us
  928. else
  929. curl http://sprunge.us/$1
  930. fi
  931. }
  932. dpaste(){
  933. # http://dpaste.de
  934. if test -z "$1"
  935. then
  936. curl -F 'content=<-' https://dpaste.de/api/
  937. echo
  938. else
  939. curl https://dpaste.de/$1/raw/
  940. fi
  941. }
  942. ######################################
  943. ## Prompt Settings
  944. __my_moc_state(){
  945. type mocp >/dev/null 2>&1 || return
  946. test "`mocp -Q %state 2>/dev/null`" = PLAY || return
  947. printf "$1" "`mocp -Q %title 2>/dev/null`"
  948. }
  949. __my_parse_svn_branch() {
  950. ___svn_url=$(LANG=C svn info 2>/dev/null | sed -ne 's#^URL: ##p')
  951. ___svn_repository_root=$(LANG=C svn info 2>/dev/null | \
  952. sed -ne 's#^Repository Root: ##p')
  953. echo ${___svn_url} | sed -e 's#^'"${___svn_repository_root}"'##g' | \
  954. awk '{print $1}'
  955. }
  956. __my_svn_ps1(){
  957. if svn status >/dev/null 2>&1
  958. then
  959. ___svn_branch=$(__my_parse_svn_branch)
  960. test -n "${___svn_branch}" && printf "$1" "{$___svn_branch}"
  961. fi
  962. }
  963. __my_battery_status(){
  964. ___dir=/sys/class/power_supply/BAT0
  965. if test -d $___dir && test -r $___dir/status && test -r $___dir/charge_full && \
  966. test -r $___dir/charge_now
  967. then
  968. ___st=$(cat $___dir/status)
  969. ___full=$(cat $___dir/charge_full)
  970. ___now=$(cat $___dir/charge_now)
  971. ___rate=$(expr $now \* 100 / $full)
  972. printf "$1" "${___st}:${___rate}%"
  973. fi
  974. }
  975. alias bat='__my_battery_status %s\\n'
  976. __my_ps1_scale(){
  977. if null type stty && ! $ismsys
  978. then
  979. echo "[LxC:`stty size | tr -d $'\n' | tr " " x`]"
  980. fi
  981. }
  982. __my_ps1_tmux(){
  983. null type tmux || return $last
  984. ___tmuxc="$(tmux display -p '#S:#I:#W.#P' 2>/dev/null)"
  985. test -n "$TMUX" && echo "[TMUX:$___tmuxc]"
  986. }
  987. __my_ps1_moc(){
  988. __my_moc_state "[MOC:%s]"
  989. }
  990. for f in /usr/share/git/git-prompt.sh \
  991. /usr/share/git-core/contrib/completion/git-prompt.sh \
  992. /usr/local/share/git-core/contrib/completion/git-prompt.sh \
  993. /etc/bash_completion.d/git-prompt \
  994. /opt/local/share/git-core/git-prompt.sh \
  995. /opt/local/share/doc/git-core/contrib/completion/git-prompt.sh
  996. do
  997. test -r "$f" && ($inbash || $inzsh) && . "$f" && break
  998. done
  999. GIT_PS1_SHOWDIRTYSTATE=t
  1000. GIT_PS1_SHOWUPSTREAM=t
  1001. __my_ps1_git(){
  1002. null type __git_ps1 || return $last
  1003. null git rev-parse --git-dir >/dev/null 2>&1 || return $last
  1004. __git_ps1 "[GIT:$(__safe_run git config --get user.name):%s]"
  1005. }
  1006. __printf_ipaddr(){
  1007. # ipaddress <fmt>
  1008. type ip >/dev/null 2>&1 || return 1
  1009. ___ip=$(LANG=C ip addr show scope global | \
  1010. \grep --color=never --only-matching 'inet [^ ]*' | cut -d " " -f 2)
  1011. test -n "$___ip" && printf "$1" $___ip
  1012. }
  1013. alias addr="__printf_ipaddr '%s
  1014. '"
  1015. __my_ps1_ipaddr(){
  1016. ! $iswindows && __printf_ipaddr '[Addr:%s]'
  1017. }
  1018. __my_ps1_bttry(){
  1019. ___bst="${TMP}/batterystatus"
  1020. if test -z "$DISPLAY" && ! $iswindows
  1021. then
  1022. test -f $___bst && ___bstr="$(cat $___bst)"
  1023. test -n "$___bstr" && ! echo $___bstr | grep 100 >/dev/null 2>&1 && \
  1024. echo "[Battery:$___bstr]"
  1025. __my_battery_status %s >$___bst &
  1026. fi
  1027. }
  1028. __my_ps1_memo(){
  1029. test -f memo.txt && echo "m:`du -b memo.txt|cut -f 1`"
  1030. }
  1031. __my_ps1_dirs(){
  1032. dirs | wc -l
  1033. }
  1034. __my_ps1_jobs(){
  1035. # __my_ps1_jobs [<num>]
  1036. if test -n "$1"
  1037. then
  1038. jobs="$1"
  1039. else
  1040. jobs="`jobs | wc -l`"
  1041. fi
  1042. if test "$jobs" -gt 0
  1043. then
  1044. echo "JOBS:$jobs"
  1045. fi
  1046. }
  1047. __my_ps1_dollar(){
  1048. if test -z "$SHLVL"
  1049. then
  1050. printf "$1"
  1051. else
  1052. perl -e 'while($ARGV[0]-- > 0){print "$ARGV[1]";}' $SHLVL "$1"
  1053. fi
  1054. }
  1055. __my_alert_fail(){
  1056. test $laststatus -eq 0 || \
  1057. echo "STATUS:${laststatus}"
  1058. }
  1059. # About ansi escape sequences
  1060. # http://archive.linux.or.jp/JF/JFdocs/Bash-Prompt-HOWTO-5.html
  1061. # http://www.grapecity.com/japan/powernews/column/clang/047/page02.htm
  1062. if $inbash || $inzsh
  1063. then
  1064. if $inzsh
  1065. then
  1066. __attr_beg=$'%{\033['
  1067. __attr_end='m%}'
  1068. else
  1069. __attr_beg='\[\033['
  1070. __attr_end='m\]'
  1071. fi
  1072. __color_default="${__attr_beg}0${__attr_end}"
  1073. __color_black="${__attr_beg}0;30${__attr_end}"
  1074. __color_red="${__attr_beg}0;31${__attr_end}"
  1075. __color_green="${__attr_beg}0;32${__attr_end}"
  1076. __color_brown="${__attr_beg}0;33${__attr_end}"
  1077. __color_blue="${__attr_beg}0;34${__attr_end}"
  1078. __color_purple="${__attr_beg}0;35${__attr_end}"
  1079. __color_cyan="${__attr_beg}0;36${__attr_end}"
  1080. __color_light_gray="${__attr_beg}0;37${__attr_end}"
  1081. __color_dark_gray="${__attr_beg}1;30${__attr_end}"
  1082. __color_light_red="${__attr_beg}1;31${__attr_end}"
  1083. __color_light_green="${__attr_beg}1;32${__attr_end}"
  1084. __color_yellow="${__attr_beg}1;33${__attr_end}"
  1085. __color_light_blue="${__attr_beg}1;34${__attr_end}"
  1086. __color_light_purple="${__attr_beg}1;35${__attr_end}"
  1087. __color_light_cyan="${__attr_beg}1;36${__attr_end}"
  1088. __color_white="${__attr_beg}1;37${__attr_end}"
  1089. __color_bg_black="${__attr_beg}40${__attr_end}"
  1090. __color_bg_red="${__attr_beg}41${__attr_end}"
  1091. __color_bg_green="${__attr_beg}42${__attr_end}"
  1092. __color_bg_brown="${__attr_beg}43${__attr_end}"
  1093. __color_bg_blue="${__attr_beg}44${__attr_end}"
  1094. __color_bg_purple="${__attr_beg}45${__attr_end}"
  1095. __color_bg_cyan="${__attr_beg}46${__attr_end}"
  1096. __color_bg_light_gray="${__attr_beg}47${__attr_end}"
  1097. __attr_underline="${__attr_beg}4${__attr_end}"
  1098. __attr_reverse="${__attr_beg}7${__attr_end}"
  1099. __attr_bold="${__attr_beg}1${__attr_end}"
  1100. fi
  1101. # NOTE: tput is another easy way to set colors and background
  1102. # For example, "$(tput setab 4)text$(tput sgr0)" print text with background
  1103. # color blue.
  1104. # http://www.ibm.com/developerworks/jp/linux/aix/library/au-learningtput/index.html
  1105. if test "$TERM" != dumb
  1106. then
  1107. __my_c1="$__attr_bold$__attr_underline" # color for PWD
  1108. __my_c2="$__attr_bold$__attr_underline" # color for user and hostname
  1109. # color for ::
  1110. case "`hostname`" in
  1111. arch-aspireone)
  1112. __my_c4="$__color_yellow"
  1113. ;;
  1114. arch-mba)
  1115. __my_c4="$__color_light_cyan"
  1116. ;;
  1117. newkiwi)
  1118. __my_c4="$__color_light_purple"
  1119. ;;
  1120. debian-vb-win7-opti)
  1121. __my_c4="$__color_light_red"
  1122. ;;
  1123. *)
  1124. __my_c4="$__color_light_green"
  1125. ;;
  1126. esac
  1127. __my_c5="$__color_black$__color_bg_light_gray" # color for SCR
  1128. __my_cdef="$__color_default"
  1129. fi
  1130. if $inbash
  1131. then
  1132. __my_ps1_sh="[BASH:$BASH_VERSION]"
  1133. elif $inzsh
  1134. then
  1135. __my_ps1_sh="[ZSH:$ZSH_VERSION]"
  1136. fi
  1137. __my_ps1_info1(){
  1138. # first line of PS1
  1139. echo "${__my_ps1_sh}$(__my_ps1_scale)$(__my_ps1_git)$(__my_ps1_bttry)$(__my_ps1_moc)"
  1140. }
  1141. test -n "$__MY_SCRIPT" && \
  1142. __my_ps1_str_scr="SCR"
  1143. test -n "$SSH_CONNECTION" && \
  1144. __my_ps1_str_ssh="SSH"
  1145. test -n "$__MY_DTACH" && \
  1146. __my_ps1_str_dt="DT:`basename "$__MY_DTACH$"`"
  1147. __my_ps1_info2(){
  1148. # second line of PS1
  1149. echo $(__my_ps1_memo) $(__my_ps1_jobs) ${__my_ps1_str_scr} \
  1150. ${__my_ps1_str_ssh} ${__my_ps1_str_dt} $(__my_alert_fail) \
  1151. | sed -e 's/ /|/g'
  1152. }
  1153. __my_ps1_beg="${__my_c4}:: ${__my_cdef}"
  1154. __my_ps1_save_pos="\[\033[s\]"
  1155. __my_ps1_restore_pos="\[\033[u\]"
  1156. __my_ps1_move_rightmost="\[\033[\$(tput cols)C\]"
  1157. __my_ps1_move_15left="\[\033[15D\]"
  1158. # collapse when command line is too long and try to write over this string
  1159. # __my_ps1_right="${__my_ps1_save_pos}${__my_ps1_move_rightmost}"
  1160. # ${__my_ps1_move_15left}\D{%Y/%m/%d %H:%M}${__my_ps1_restore_pos}
  1161. if $inzsh
  1162. then
  1163. PROMPT="\
  1164. ${__my_ps1_beg}[${__my_c2}%n@%M${__my_cdef}:${__my_c1}%~/${__my_cdef}]\$(__my_ps1_info1)
  1165. ${__my_ps1_beg}\$(__my_ps1_info2) $(__my_ps1_dollar %#) "
  1166. RPROMPT="%D{%Y/%m/%d %H:%M}"
  1167. elif $inbash
  1168. then
  1169. PS1="\
  1170. ${__my_ps1_beg}[${__my_c2}\u@\H${__my_cdef}:${__my_c1}\w/${__my_cdef}]\$(__my_ps1_info1)\n\
  1171. ${__my_ps1_beg}\D{%Y/%m/%d %H:%M} \$(__my_ps1_info2)${__my_ps1_right} $(__my_ps1_dollar \\$) "
  1172. else
  1173. true
  1174. # PS1="$(printf $(whoami)@$(hostname)$ )"
  1175. fi
  1176. ###################################
  1177. # set header and titles
  1178. __my_set_header_line(){
  1179. # save current position
  1180. printf "\033[s"
  1181. # move to 0,0
  1182. printf "\033[0;0H"
  1183. # clear curent to eol
  1184. printf "\033[K"
  1185. # inverse color
  1186. printf "\033[7m"
  1187. printf "$1"
  1188. # restore color
  1189. printf "\033[0m"
  1190. # restore saved position
  1191. printf "\033[u"
  1192. }
  1193. __my_set_screen_name(){
  1194. # set window name
  1195. if test -n "$TMUX" && test -z "$INSIDE_EMACS"
  1196. then
  1197. echo -ne "\033k$1\033\\"
  1198. fi
  1199. }
  1200. __my_set_title(){
  1201. case $TERM in
  1202. (rxvt*|xterm*|aterm|screen*)
  1203. test -t 1 &&
  1204. test -z "$EMACS" &&
  1205. echo -n -e "\033]0;$1\007"
  1206. ;;
  1207. esac
  1208. }
  1209. if test -n "$TMUX"
  1210. then
  1211. # running tmux locally
  1212. __terminal_title="\$(basename \${PWD})"
  1213. elif test -n "$SSH_CONNECTION" && expr "$TERM" : '^screen' >/dev/null
  1214. then
  1215. # ssh connect from tmux terminal
  1216. __terminal_title="`whoami`@`hostname`:\$(basename \${PWD})"
  1217. else
  1218. __terminal_title="`whoami`@`hostname`:\${PWD}"
  1219. fi
  1220. if $inzsh
  1221. then
  1222. precmd(){
  1223. laststatus=$?
  1224. eval __my_set_title ${__terminal_title}
  1225. }
  1226. else
  1227. PROMPT_COMMAND="laststatus=\$?;__my_set_title \"${__terminal_title}\";$PROMPT_COMMAND"
  1228. fi
  1229. laststatus=0