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.
 
 
 
 
 
 

1388 line
32 KiB

  1. #!/bin/sh
  2. expr "$-" : '^.*i' >/dev/null || return
  3. ##########################################
  4. __shrc_lock=/tmp/shrc_lock.$USER.$$
  5. test -f "$__shrc_lock" && return
  6. touch "$__shrc_lock"
  7. ##########################################
  8. null(){
  9. "$@" >/dev/null 2>&1
  10. }
  11. __safe_run(){
  12. type $1 >/dev/null 2>&1 && "$@"
  13. }
  14. __match(){
  15. # __match str word
  16. # return 0 if word is found in str
  17. expr "$1" : ".*$2.*" >/dev/null
  18. }
  19. #################################
  20. # profile-like setups
  21. __safe_add_path_r(){
  22. # add path to right
  23. test -d "$1" && PATH="${PATH}:$1"
  24. }
  25. __safe_add_path_l(){
  26. # add path to left
  27. test -d "$1" && PATH="$1:${PATH}"
  28. }
  29. __safe_add_path_l "$HOME/.cabal/bin"
  30. __safe_add_path_l "$HOME/.local/lib/gems/bin"
  31. __safe_add_path_l "$HOME/.local/bin"
  32. __safe_add_path_l "$HOME/.gem/ruby/2.1.0/bin"
  33. __safe_add_path_r "/c/mingw/bin"
  34. __safe_add_path_r "/c/mingw/msys/1.0/bin"
  35. # macports coreutils
  36. # $isdarwin cannot be used it is not defined yet
  37. __safe_add_path_l "/opt/local/bin"
  38. __safe_add_path_l "/opt/local/sbin"
  39. __safe_add_path_l "/opt/local/libexec/gnubin"
  40. __safe_add_path_l \
  41. "/opt/local/Library/Frameworks/Python.framework/Versions/3.2/bin"
  42. test -f "${__dotdir}/rc.py" && export PYTHONSTARTUP="${__dotdir}/rc.py"
  43. test -d "$HOME/.local/lib/python/site-packages" && \
  44. export PYTHONPATH="${PYTHONPATH}:${HOME}/.local/lib/python/site-packages"
  45. export GEM_HOME="$HOME/.local/lib/gems"
  46. export RUBYLIB="$RUBYLIB:$HOME/.local/lib/gems/lib"
  47. # it is not so good
  48. # http://archive.linux.or.jp/JF/JFdocs/Program-Library-HOWTO/shared-libraries.html
  49. # http://superuser.com/questions/324613/installing-a-library-locally-in-home-directory-but-program-doesnt-recognize-it
  50. # without this ENV i cannot run tmux. another way is to use --disable-shared
  51. # when building tmux
  52. if ! __match "$LD_LIBRARY_PATH" "$HOME/.local/lib"
  53. then
  54. export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$HOME/.local/lib"
  55. fi
  56. # in my environment powerdown does not work
  57. test -z "$DISPLAY" && test -z "$SSH_CONNECTION" && \
  58. type setterm >/dev/null 2>&1 && \
  59. setterm -blank 30 -powersave on # -powerdown 10
  60. #########################
  61. # shrc.common
  62. # this variable must consistent with setup.sh
  63. __shrc_common="$HOME/.shrc.common"
  64. if test -f "$__shrc_common"
  65. then
  66. . "$__shrc_common"
  67. else
  68. echo "$__shrc_common not found."
  69. echo "Run setup.sh first."
  70. return
  71. fi
  72. ##########################
  73. # system type
  74. gnu_coreutils=false # for mac
  75. null ls --version && gnu_coreutils=true
  76. inbash=false
  77. inzsh=false
  78. if test -n "$BASH_VERSION"
  79. then
  80. inbash=true
  81. elif test -n "$ZSH_VERSION"
  82. then
  83. inzsh=true
  84. fi
  85. #################################
  86. # file pathes:
  87. # shrc: Path to this file
  88. if $inbash
  89. then
  90. __shrc="$BASH_SOURCE"
  91. elif $inzsh
  92. then
  93. __shrc="$0"
  94. fi
  95. ##################################
  96. # EnvVal definitions
  97. test "$TERM" = linux && export LANG=C
  98. export LC_MESSAGES=C
  99. export LC_TIME=C
  100. export TERMCAP="${TERMCAP}:vb="
  101. $ismsys && export HOSTNAME
  102. # export ENV=~/.shrc
  103. if false $iswindows
  104. then
  105. export PAGER='tr -d \\r | less'
  106. else
  107. export PAGER="less"
  108. fi
  109. export LESS="-iRMX"
  110. # Style for lesspipe is defined in esc.style
  111. _src_hilite_lp_path="`command -v src-hilite-lesspipe.sh 2>/dev/null`"
  112. for f in /usr/share/source-highlight/src-hilite-lesspipe.sh
  113. do
  114. test -z "$_src_hilite_lp_path" && test -e "$f" && _src_hilite_lp_path="$f"
  115. done
  116. test -n "$_src_hilite_lp_path" && export LESSOPEN="| $_src_hilite_lp_path %s"
  117. if null type vim
  118. then
  119. export EDITOR=vim
  120. else
  121. export EDITOR=vi
  122. fi
  123. # export CDPATH=".:~"
  124. export VISUAL="$EDITOR"
  125. export GIT_PAGER="less -F"
  126. export GIT_EDITOR="$EDITOR"
  127. export GIT_MERGE_AUTOEDIT=no
  128. if test -n "$TMUX" && \
  129. __match $TERM screen && \
  130. __match `tmux display -p '#{client_termname}'` 256color
  131. then
  132. TERM=screen-256color
  133. fi
  134. # set TMP, TEMP, TMPDIR
  135. if test -z "$TMP"
  136. then
  137. if test -n "$TMPDIR"
  138. then
  139. export TMP=$TMPDIR
  140. elif test -n "$TEMP"
  141. then
  142. export TMP="$TEMP"
  143. else
  144. export TMP=/tmp
  145. fi
  146. fi
  147. __match "$TMP" "${USER}-tmp" >/dev/null || TMP="${TMP}/${USER}-tmp"
  148. test -d "$TMP" || mkdir -p "$TMP"
  149. export TEMP=$TMP
  150. export TMPDIR=$TMP
  151. if ! $iswindows && null type stty
  152. then
  153. stty stop undef # unbind C-s to stop displaying output
  154. # stty erase '^h'
  155. fi
  156. if $iswindows
  157. then
  158. export USER=$USERNAME
  159. fi
  160. if test -d ~/dbx
  161. then
  162. export CHIT_PATH="$HOME/dbx/.chit"
  163. fi
  164. # adhoc fix for ansible on cygwin
  165. # http://blog.s-uni.net/2013/08/27/ansible-running-on-cygwin/
  166. if $incygwin
  167. then
  168. export ANSIBLE_SSH_ARGS="-o ControlMaster=no"
  169. fi
  170. ##########################
  171. # Zsh specific preferences
  172. # http://www.clear-code.com/blog/2011/9/5.html
  173. if $inzsh
  174. then
  175. bindkey -e
  176. # http://zsh.sourceforge.net/Guide/zshguide06.html#l147
  177. autoload compinit; compinit
  178. # supress cycle by tab
  179. unsetopt auto_menu
  180. # unsetopt correct
  181. setopt complete_aliases
  182. setopt auto_list
  183. setopt bash_auto_list
  184. setopt magic_equal_subst
  185. setopt list_types
  186. # what is the difference of these two?
  187. setopt auto_param_slash
  188. setopt mark_dirs
  189. zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
  190. zstyle ':completion:*' format '%B%d%b'
  191. zstyle ':completion:*' group-name ''
  192. zstyle ':completion:*' use-cache yes
  193. # zstyle ':completion:*:cd:*' tag-order local-directories
  194. zstyle ':completion:*' completer _complete _bash_completions \
  195. _history
  196. # zstyle ':completion:*:*:cd:*' completer
  197. zstyle ':completion:*' accept-exact-dirs true
  198. zstyle ':completion:*' special-dirs true
  199. autoload colors; colors
  200. # autoload -Uz promptinit
  201. # promptinit
  202. # prompt walters
  203. setopt hist_ignore_dups
  204. setopt hist_ignore_all_dups
  205. setopt hist_save_no_dups
  206. setopt extended_history
  207. setopt share_history
  208. setopt append_history
  209. HISTFILE=$HOME/.zsh-history
  210. HISTSIZE=100000
  211. SAVEHIST=100000
  212. setopt prompt_subst
  213. setopt interactive_comments
  214. fi
  215. ######################
  216. # Print welcome messages
  217. command -v fortune >/dev/null && {
  218. if command -v cowsay >/dev/null
  219. then
  220. fortune | cowsay
  221. echo
  222. fortune -o | cowsay
  223. echo
  224. else
  225. fortune
  226. echo
  227. fortune -o
  228. echo
  229. fi
  230. }
  231. uname -a
  232. $iswindows && alias tty="echo cmd.exe"
  233. echo TERM $TERM with $(tput colors) colors using $(tty)
  234. echo
  235. __safe_run w yuk
  236. # if null type tmux
  237. # then
  238. # echo
  239. # echo tmux sessions:
  240. # tmux ls 2>/dev/null| sed -e 's/^/ /g'
  241. # echo
  242. # fi
  243. # if test -n "$TMUX"
  244. # then
  245. # tmux display -p \
  246. # 'TMUX #S:#I:#W.#P, client TERM: #{client_termname}' \
  247. # 2>/dev/null
  248. # echo
  249. # fi
  250. ###################################
  251. # some aliases and functions
  252. # __func_name: never used interactively
  253. # _func_name: usually not used interactively
  254. __safe_alias(){
  255. # __safe_alias <name>=<command>
  256. _bin=`expr "$1" : '^[^=]*=\([^ ]*\)'`
  257. test -n "$_bin" && \
  258. null type $_bin && \
  259. alias "$1"
  260. }
  261. $gnu_coreutils && _timeoption=" --time-style=long-iso"
  262. # color prefs
  263. if $gnu_coreutils
  264. then
  265. # http://qiita.com/yuyuchu3333/items/84fa4e051c3325098be3
  266. # gnu coreutils LS_COLORS is used
  267. null type dircolors && eval `dircolors`
  268. _coloroption=" --color=auto"
  269. else
  270. # export LSCOLORS=gxfxcxdxbxegedabagacad
  271. export LSCOLORS=DxGxcxdxCxegedabagacad
  272. export CLICOLOR=1
  273. fi
  274. alias ls="ls -hCF${_coloroption}${_timeoption}"
  275. _timeformat_iso="%Y-%m-%dT%H:%M:%S%z"
  276. _timeformat_rfc2822="%a, %d %b %Y %T %z"
  277. _timeformat_num="%Y%m%d%H%M%S"
  278. alias datenum="date +$_timeformat_num"
  279. # export GREP_OPTIONS=""
  280. alias gr="grep -n --color=always"
  281. $iswindows && alias gr="grep -n"
  282. alias less="less -F"
  283. __safe_alias em="emacs -nw"
  284. __safe_alias vi=vim
  285. alias pstree="LANG=C pstree"
  286. alias cp="cp -v"
  287. alias mv="mv -v"
  288. alias rm="rm -v"
  289. alias mkdir="mkdir -v"
  290. alias rmdir="rmdir -v"
  291. alias psaux="ps auxww"
  292. alias q=exit
  293. __safe_alias e3=e3em
  294. #alias dirs="dirs -v -l | \grep -v \$(printf '%s$' \$PWD)"
  295. alias po=popd
  296. alias pu=pushd
  297. __safe_alias sudo="sudo " # use aliases through sudo
  298. __safe_alias sudoe="sudoedit"
  299. # __safe_alias halt="sudo halt"
  300. # __safe_alias reboot="sudo reboot"
  301. null type dbus-send && {
  302. alias suspend="dbus-send --system --print-reply \
  303. --dest=org.freedesktop.UPower \
  304. /org/freedesktop/UPower org.freedesktop.UPower.Suspend"
  305. alias hibernate="dbus-send --system --print-reply \
  306. --dest=org.freedesktop.UPower \
  307. /org/freedesktop/UPower org.freedesktop.UPower.Hibernate"
  308. }
  309. alias rand="echo \$RANDOM"
  310. __safe_alias xunp="file-roller -h"
  311. __safe_alias pc="sudo \paco -D"
  312. alias pycalc="python -i -c 'from math import *' "
  313. __safe_alias py3=python3
  314. __safe_alias py2=python2
  315. __safe_alias ipy=ipython
  316. __safe_alias ipy3=ipython3
  317. __safe_alias ipy2=ipython2
  318. # Sometimes SHELL cannot be used. For example, when running bash inside zsh
  319. # SHELL is set to be /bin/zsh
  320. if $inbash
  321. then
  322. alias _reloadrc="rm '$__shrc_lock'; exec bash"
  323. elif $inzsh
  324. then
  325. alias _reloadrc="rm '$__shrc_lock'; exec zsh"
  326. else
  327. alias _reloadrc="rm '$__shrc_lock'; exec $SHELL"
  328. fi
  329. # alias mytime="date +%Y%m%d-%H%M%S"
  330. alias sh="ENV=$HOME/.shrc PS1=\$\ PROMPT_COMMAND="" sh"
  331. # type trash >/dev/null 2>&1 && alias rm=trash
  332. __safe_alias mpg123="mpg123 -C -v --title"
  333. __safe_alias xm="xmms2"
  334. #export PLAYER="mpg123 -C -v --title"
  335. __safe_alias screen="screen -e^z^z"
  336. #alias zcd="cd \`zenity --file-selection --directory\`"
  337. __safe_alias gtags="gtags --verbose"
  338. __safe_alias htags="htags --xhtml --symbol --line-number \
  339. --frame --alphabet --verbose"
  340. __safe_alias au=aunpack
  341. # __safe_alias lv="lv|less"
  342. __safe_alias rs="rsync --progress --itemize-changes --compress"
  343. __safe_alias vagr=vagrant
  344. if $iscygwin
  345. then
  346. __my_wget_options=" --no-check-certificate"
  347. __safe_alias wget="wget $__my_wget_options"
  348. fi
  349. if $isdarwin
  350. then
  351. alias updatedb="LC_ALL=C updatedb"
  352. # do not use locate installed by macports
  353. test -x /usr/bin/locate && alias locate="/usr/bin/locate"
  354. fi
  355. # somehow not work
  356. # typeset -ga chpwd_functions
  357. # chpwd_functions+=pwd
  358. # chpwd(){
  359. # pwd
  360. # }
  361. cd(){
  362. builtin cd "$@" && pwd
  363. }
  364. # pad
  365. alias pad=notepad
  366. __safe_alias pad=gedit
  367. __safe_alias pad=leafpad
  368. $isdarwin && alias pad="open -e"
  369. __safe_alias wic=wicd-curses
  370. __safe_alias wil="wicd-cli -y -l | head"
  371. #alias wicn="wicd-cli -y -c -n"
  372. wicn(){
  373. if test $# -eq 0
  374. then
  375. local num
  376. wicd-cli -y -l | head
  377. echo -n "input num: "
  378. read num
  379. test -n "$num" && wicd-cli -y -c -n $num
  380. else
  381. wicd-cli -y -c -n $1
  382. fi
  383. }
  384. __find_latest_vimdir(){
  385. vimdir=/usr/share/vim
  386. if test -d "$vimdir"
  387. then
  388. find "$vimdir" -name 'vim??' -type d | sort | tail -n 1
  389. else
  390. echo ""
  391. fi
  392. }
  393. for f in /usr/share/vim/vimcurrent "`__find_latest_vimdir`"
  394. do
  395. test -n "$f" || continue
  396. f="$f/macros/less.sh"
  397. test -f $f && alias vl=$f && break
  398. done
  399. __safe_alias pa="pacman --color=always"
  400. __safe_alias pa="pacapt"
  401. __safe_alias yt=yaourt
  402. __safe_alias cower="cower --color=auto"
  403. null type pacmatic && {
  404. alias pacman="pacmatic"
  405. # variable for yaourt
  406. export PACMAN="pacmatic"
  407. }
  408. __my_pacman_update_mirrorlist_with_reflector(){
  409. ml=/etc/pacman.d/mirrorlist
  410. cmd="$(expr "$(grep -m 1 reflector $ml)" : '# With: *\(.*\)')"
  411. if test -z "$cmd"
  412. then
  413. cmd="reflector --verbose --country Japan --latest 5 --sort rate --save $ml"
  414. fi
  415. echo ">>> $cmd ..." 1>&2
  416. sudo sh -c "$cmd"
  417. }
  418. null type reflector && test -d /etc/pacman.d && \
  419. alias reflect_mirrorlist=__my_pacman_update_mirrorlist_with_reflector
  420. null type apt-get && {
  421. alias aupgrade="sudo sh -xc 'apt-get autoremove --yes && \
  422. apt-get update --yes && apt-get upgrade --yes'"
  423. alias aptin="apt-get install"
  424. alias aptsearch="apt-cache search"
  425. alias aptshow="apt-cache show"
  426. }
  427. null type port && {
  428. alias port="port -v"
  429. alias pupgrade="sudo sh -xc 'port -v selfupdate && \
  430. port -v upgrade outdated'"
  431. }
  432. if $iscygwin
  433. then
  434. null type windate || \
  435. alias windate="cmd.exe //c 'echo %DATE%-%TIME%'"
  436. # alias cygsu="cygstart /cygwinsetup.exe"
  437. fi
  438. mkpatch(){
  439. if test $# -eq 0
  440. then
  441. echo "usage: mkpatch <olddir> <newdir>"
  442. elif ! test -d "$1"
  443. then
  444. echo "mkpatch: $1 is not a directory"
  445. elif ! test -d "$2"
  446. then
  447. echo "mkpatch: $2 is not a directory"
  448. else
  449. diff -Naur "$1" "$2"
  450. fi
  451. }
  452. g(){
  453. if test $# -eq 0 && null type git-info
  454. then
  455. git info
  456. else
  457. git -c color.ui=always "$@"
  458. fi
  459. }
  460. if null type _git && $inbash
  461. then
  462. # enable programmable completion for g
  463. complete -o bashdefault -o default -o nospace -F _git g 2>/dev/null \
  464. || complete -o default -o nospace -F _git g
  465. fi
  466. #git svn --help >/dev/null 2>&1 && alias gsvn="git svn"
  467. __safe_alias m=gitmemo
  468. alias setup.py3="sudo python3 setup.py install --record files.txt"
  469. randomstr(){
  470. len=$1
  471. test -z "$len" && len=8
  472. uuidgen | tr -d - | cut -c 1-len
  473. }
  474. datestr(){
  475. # datestr YYYYMMDDhhmmss
  476. if test -z "$1" || test "$1" = "-h"
  477. then
  478. echo "datestr: usage: datestr <YYYYMMDDhhmmss>"
  479. return 1
  480. fi
  481. dfmt="" # actual format for date command
  482. while test -n "$1"
  483. do
  484. fmt="$1"
  485. shift
  486. while test -n "$fmt"
  487. do
  488. case "$fmt" in
  489. YYYY*|yyyy*) # year
  490. dfmt="${dfmt}%Y"
  491. fmt="`echo "$fmt" | cut -c 5-`"
  492. ;;
  493. YY*|yy*) # last two digits of year
  494. dfmt="${dfmt}%y"
  495. fmt="`echo "$fmt" | cut -c 3-`"
  496. ;;
  497. MM*) # month (01..12)
  498. dfmt="${dfmt}%m"
  499. fmt="`echo "$fmt" | cut -c 3-`"
  500. ;;
  501. DD*|dd*) # day of month (01..12)
  502. dfmt="${dfmt}%d"
  503. fmt="`echo "$fmt" | cut -c 3-`"
  504. ;;
  505. HH* | hh*) # hour (00..23)
  506. dfmt="${dfmt}%H"
  507. fmt="`echo "$fmt" | cut -c 3-`"
  508. ;;
  509. mm*) # minute (00..59)
  510. dfmt="${dfmt}%M"
  511. fmt="`echo "$fmt" | cut -c 3-`"
  512. ;;
  513. SS*|ss*) # second (00..60)
  514. dfmt="${dfmt}%S"
  515. fmt="`echo "$fmt" | cut -c 3-`"
  516. ;;
  517. *)
  518. char=`echo "$fmt" | cut -c 1`
  519. dfmt="${dfmt}${char}"
  520. fmt="`echo "$fmt" | cut -c 2-`"
  521. ;;
  522. esac
  523. done
  524. done
  525. date +"$dfmt"
  526. }
  527. # ssh(){
  528. # # __my_terminal_title ssh
  529. # command ssh "$@"
  530. # }
  531. __ssh_with_cd(){
  532. # __ssh_with_cd <host> <directory> [<arg> ...]
  533. if test -z "$2"
  534. then
  535. echo "usage: __ssh_with_cd <host> <directory> [<arg> ...]"
  536. return 1
  537. fi
  538. host="$1"
  539. shift
  540. dir="$1"
  541. shift
  542. ssh "$host" "$@" -t "cd \"$dir\"; \$SHELL -l"
  543. }
  544. memo(){
  545. if test -z "$1"
  546. then
  547. _memo="memo.txt"
  548. else
  549. _memo="$1/memo.txt"
  550. fi
  551. $EDITOR "$_memo"
  552. if test -z "`cat "$_memo"`"
  553. then
  554. echo "$_memo is empty. Removing."
  555. rm "$_memo"
  556. fi
  557. }
  558. now(){
  559. local tformat="%Y/%m/%d %H:%M:%S %z"
  560. cal
  561. REPLY=
  562. printf "\\r`date "+${tformat}"`"
  563. read -t 1
  564. while test $? -ne 0
  565. do
  566. printf "\\r`date "+${tformat}"`"
  567. read -t 1
  568. done
  569. }
  570. s(){
  571. if git rev-parse --git-dir >/dev/null 2>&1
  572. then
  573. echo ">> git grep -n $@" 1>&2
  574. git grep -n "$@"
  575. elif which ag >/dev/null 2>&1
  576. then
  577. echo ">> ag --pager=\"$PAGER\" $@" 1>&2
  578. ag --pager="$PAGER" "$@"
  579. elif which ack >/dev/null 2>&1
  580. then
  581. echo ">> ack --pager=\"$PAGER\" $@" 1>&2
  582. ack --pager="$PAGER" "$@"
  583. else
  584. echo \
  585. ">> find . " \
  586. "-path '*/.git' -prune -o" \
  587. "-path '*/.svn' -prune -o" \
  588. "-type f -exec grep -nH -e --color=always $@ {} +" 1>&2
  589. if test $# -eq 0
  590. then
  591. echo "No search word given." 1>&2
  592. return 1
  593. fi
  594. find . \
  595. -path '*/.git' -prune -o \
  596. -path '*/.svn' -prune -o \
  597. -type -f -exec grep -nH -e --color=always "$@" {} + \
  598. | $PAGER
  599. fi
  600. }
  601. MYMANPATH='/usr/lib/erlang/man'
  602. if $inbash || $inzsh
  603. then
  604. man(){
  605. env \
  606. LESS_TERMCAP_mb=$(printf "\e[1;35m") \
  607. LESS_TERMCAP_md=$(printf "\e[1;31m") \
  608. LESS_TERMCAP_me=$(printf "\e[0m") \
  609. LESS_TERMCAP_se=$(printf "\e[0m") \
  610. LESS_TERMCAP_so=$(printf "\e[1;44;33m") \
  611. LESS_TERMCAP_ue=$(printf "\e[0m") \
  612. LESS_TERMCAP_us=$(printf "\e[1;32m") \
  613. MANPATH="`manpath`:$MYMANPATH" \
  614. man "$@"
  615. }
  616. fi
  617. netwait(){
  618. while ! ping -c 1 -t 1 example.com
  619. do
  620. true
  621. done
  622. echo network works.
  623. }
  624. __realpath(){
  625. if type realpath >/dev/null 2>&1
  626. then
  627. command realpath "$@"
  628. else
  629. while ! test -d $1
  630. do
  631. shift
  632. done
  633. (command cd "$d" && echo "$PWD")
  634. # local d="$OLDPWD"
  635. # command cd "$1"
  636. # echo "$PWD"
  637. # command cd "$d"
  638. fi
  639. }
  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. local _tformat="%Y%m%d-%H%M%S%z"
  706. local _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. local _cmdstr="`echo $@ | tr ' ' +`"
  717. local _tformat="%Y%m%d-%H%M%S%z"
  718. local _name="${pf}`date +${_tformat}`-${_cmdstr}"
  719. local _scr_file="${HOME}/${_name}.script"
  720. local _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. local srcs="$2"
  751. local dsts="$3"
  752. test -z "$dsts" && dsts="${srcs}.out"
  753. local 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. local 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. local diffcmd=colordiff
  809. else
  810. local 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. local LANG=C
  951. local svn_url=$(svn info 2>/dev/null | sed -ne 's#^URL: ##p')
  952. local svn_repository_root=$(svn info 2>/dev/null | \
  953. sed -ne 's#^Repository Root: ##p')
  954. echo ${svn_url} | sed -e 's#^'"${svn_repository_root}"'##g' | \
  955. awk '{print $1}'
  956. }
  957. __my_svn_ps1(){
  958. if svn status >/dev/null 2>&1
  959. then
  960. local svn_branch=$(__my_parse_svn_branch)
  961. test -n "${svn_branch}" && printf "$1" "{$svn_branch}"
  962. fi
  963. }
  964. __my_battery_status(){
  965. local dir=/sys/class/power_supply/BAT0
  966. if test -d $dir && test -r $dir/status && test -r $dir/charge_full && \
  967. test -r $dir/charge_now
  968. then
  969. local st=$(cat $dir/status)
  970. local full=$(cat $dir/charge_full)
  971. local now=$(cat $dir/charge_now)
  972. local rate=$(expr $now \* 100 / $full)
  973. printf "$1" "${st}:${rate}%"
  974. fi
  975. }
  976. alias bat='__my_battery_status %s\\n'
  977. ipaddress(){
  978. # ipaddress <fmt>
  979. type ip >/dev/null 2>&1 || return 1
  980. local ip=$(LANG=C ip addr show scope global | \
  981. \grep --color=never --only-matching 'inet [^ ]*' | cut -d " " -f 2)
  982. test -n "$ip" && printf $1 $ip
  983. }
  984. __my_ps1_scale(){
  985. if null type stty && ! $ismsys
  986. then
  987. echo "[LxC:`stty size | tr -d $'\n' | tr " " x`]"
  988. fi
  989. }
  990. __my_ps1_tmux(){
  991. null type tmux || return $last
  992. local tmuxc="$(tmux display -p '#S:#I:#W.#P' 2>/dev/null)"
  993. test -n "$TMUX" && echo "[TMUX:$tmuxc]"
  994. }
  995. __my_ps1_moc(){
  996. __my_moc_state "[MOC:%s]"
  997. }
  998. for f in /usr/share/git/git-prompt.sh \
  999. /usr/local/share/git-core/contrib/completion/git-prompt.sh \
  1000. /etc/bash_completion.d/git-prompt \
  1001. /opt/local/share/git-core/git-prompt.sh \
  1002. /opt/local/share/doc/git-core/contrib/completion/git-prompt.sh
  1003. do
  1004. test -r "$f" && ($inbash || $inzsh) && . "$f" && break
  1005. done
  1006. GIT_PS1_SHOWDIRTYSTATE=t
  1007. GIT_PS1_SHOWUPSTREAM=t
  1008. __my_ps1_git(){
  1009. null type __git_ps1 || return $last
  1010. null git rev-parse --git-dir >/dev/null 2>&1 || return $last
  1011. __git_ps1 "[GIT:$(__safe_run git config --get user.name):%s]"
  1012. }
  1013. __my_ps1_ipaddr(){
  1014. ! $iswindows && ipaddress '[Addr:%s]'
  1015. }
  1016. __my_ps1_bttry(){
  1017. local bst="${TMP}/batterystatus"
  1018. if test -z "$DISPLAY" && ! $iswindows
  1019. then
  1020. test -f $bst && local bstr="$(cat $bst)"
  1021. test -n "$bstr" && ! echo $bstr | grep 100 >/dev/null 2>&1 && \
  1022. echo "[Battery:$bstr]"
  1023. __my_battery_status %s >$bst &
  1024. fi
  1025. }
  1026. __my_ps1_memo(){
  1027. test -f memo.txt && echo "m:`du -b memo.txt|cut -f 1`"
  1028. }
  1029. __my_ps1_dirs(){
  1030. dirs | wc -l
  1031. }
  1032. __my_ps1_jobs(){
  1033. # __my_ps1_jobs [<num>]
  1034. if test -n "$1"
  1035. then
  1036. jobs="$1"
  1037. else
  1038. jobs="`jobs | wc -l`"
  1039. fi
  1040. if test "$jobs" -gt 0
  1041. then
  1042. echo "JOBS:$jobs"
  1043. fi
  1044. }
  1045. __my_alert_fail(){
  1046. test $laststatus -eq 0 || \
  1047. echo "STATUS:${laststatus}"
  1048. }
  1049. # About ansi escape sequences
  1050. # http://archive.linux.or.jp/JF/JFdocs/Bash-Prompt-HOWTO-5.html
  1051. # http://www.grapecity.com/japan/powernews/column/clang/047/page02.htm
  1052. if $inbash || $inzsh
  1053. then
  1054. if $inzsh
  1055. then
  1056. __attr_beg=$'%{\033['
  1057. __attr_end='m%}'
  1058. else
  1059. __attr_beg='\[\033['
  1060. __attr_end='m\]'
  1061. fi
  1062. __color_default="${__attr_beg}0${__attr_end}"
  1063. __color_black="${__attr_beg}0;30${__attr_end}"
  1064. __color_red="${__attr_beg}0;31${__attr_end}"
  1065. __color_green="${__attr_beg}0;32${__attr_end}"
  1066. __color_brown="${__attr_beg}0;33${__attr_end}"
  1067. __color_blue="${__attr_beg}0;34${__attr_end}"
  1068. __color_purple="${__attr_beg}0;35${__attr_end}"
  1069. __color_cyan="${__attr_beg}0;36${__attr_end}"
  1070. __color_light_gray="${__attr_beg}0;37${__attr_end}"
  1071. __color_dark_gray="${__attr_beg}1;30${__attr_end}"
  1072. __color_light_red="${__attr_beg}1;31${__attr_end}"
  1073. __color_light_green="${__attr_beg}1;32${__attr_end}"
  1074. __color_yellow="${__attr_beg}1;33${__attr_end}"
  1075. __color_light_blue="${__attr_beg}1;34${__attr_end}"
  1076. __color_light_purple="${__attr_beg}1;35${__attr_end}"
  1077. __color_light_cyan="${__attr_beg}1;36${__attr_end}"
  1078. __color_white="${__attr_beg}1;37${__attr_end}"
  1079. __color_bg_black="${__attr_beg}40${__attr_end}"
  1080. __color_bg_red="${__attr_beg}41${__attr_end}"
  1081. __color_bg_green="${__attr_beg}42${__attr_end}"
  1082. __color_bg_brown="${__attr_beg}43${__attr_end}"
  1083. __color_bg_blue="${__attr_beg}44${__attr_end}"
  1084. __color_bg_purple="${__attr_beg}45${__attr_end}"
  1085. __color_bg_cyan="${__attr_beg}46${__attr_end}"
  1086. __color_bg_light_gray="${__attr_beg}47${__attr_end}"
  1087. __attr_underline="${__attr_beg}4${__attr_end}"
  1088. __attr_reverse="${__attr_beg}7${__attr_end}"
  1089. __attr_bold="${__attr_beg}1${__attr_end}"
  1090. fi
  1091. # NOTE: tput is another easy way to set colors and background
  1092. # For example, "$(tput setab 4)text$(tput sgr0)" print text with background
  1093. # color blue.
  1094. # http://www.ibm.com/developerworks/jp/linux/aix/library/au-learningtput/index.html
  1095. if test "$TERM" != dumb
  1096. then
  1097. __my_c1="$__attr_bold$__attr_underline" # color for PWD
  1098. __my_c2="$__attr_bold$__attr_underline" # color for user and hostname
  1099. # color for ::
  1100. case "`hostname`" in
  1101. arch-aspireone)
  1102. __my_c4="$__color_yellow"
  1103. ;;
  1104. arch-mba)
  1105. __my_c4="$__color_light_cyan"
  1106. ;;
  1107. newkiwi)
  1108. __my_c4="$__color_light_purple"
  1109. ;;
  1110. freebsd-vb-win7-opti)
  1111. __my_c4="$__color_light_red"
  1112. ;;
  1113. *)
  1114. __my_c4="$__color_light_green"
  1115. ;;
  1116. esac
  1117. __my_c5="$__color_black$__color_bg_light_gray" # color for SCR
  1118. __my_cdef="$__color_default"
  1119. fi
  1120. if $inbash
  1121. then
  1122. __my_ps1_sh="[BASH:$BASH_VERSION]"
  1123. elif $inzsh
  1124. then
  1125. __my_ps1_sh="[ZSH:$ZSH_VERSION]"
  1126. fi
  1127. __my_ps1_info1(){
  1128. # first line of PS1
  1129. echo "${__my_ps1_sh}$(__my_ps1_scale)$(__my_ps1_git)$(__my_ps1_bttry)$(__my_ps1_ipaddr)$(__my_ps1_moc)"
  1130. }
  1131. test -n "$__MY_SCRIPT" && \
  1132. __my_ps1_str_scr="SCR"
  1133. test -n "$SSH_CONNECTION" && \
  1134. __my_ps1_str_ssh="SSH"
  1135. test -n "$__MY_DTACH" && \
  1136. __my_ps1_str_dt="DT:`basename "$__MY_DTACH$"`"
  1137. __my_ps1_info2(){
  1138. # second line of PS1
  1139. echo $(__my_ps1_memo) $(__my_ps1_jobs) ${__my_ps1_str_scr} \
  1140. ${__my_ps1_str_ssh} ${__my_ps1_str_dt} $(__my_alert_fail) \
  1141. | sed -e 's/ /|/g'
  1142. }
  1143. __my_ps1_beg="${__my_c4}:: ${__my_cdef}"
  1144. __my_ps1_save_pos="\[\033[s\]"
  1145. __my_ps1_restore_pos="\[\033[u\]"
  1146. __my_ps1_move_rightmost="\[\033[\$(tput cols)C\]"
  1147. __my_ps1_move_15left="\[\033[15D\]"
  1148. # collapse when command line is too long and try to write over this string
  1149. # __my_ps1_right="${__my_ps1_save_pos}${__my_ps1_move_rightmost}"
  1150. # ${__my_ps1_move_15left}\D{%Y/%m/%d %H:%M}${__my_ps1_restore_pos}
  1151. if $inzsh
  1152. then
  1153. PROMPT="\
  1154. ${__my_ps1_beg}[${__my_c2}%n@%M${__my_cdef}:${__my_c1}%~/${__my_cdef}]\$(__my_ps1_info1)
  1155. ${__my_ps1_beg}\$(__my_ps1_info2) %# "
  1156. RPROMPT="%D{%Y/%m/%d %H:%M}"
  1157. elif $inbash
  1158. then
  1159. PS1="\
  1160. ${__my_ps1_beg}[${__my_c2}\u@\H${__my_cdef}:${__my_c1}\w/${__my_cdef}]\$(__my_ps1_info1)\n\
  1161. ${__my_ps1_beg}\D{%Y/%m/%d %H:%M} \$(__my_ps1_info2)${__my_ps1_right} \$ "
  1162. else
  1163. true
  1164. # PS1="$(printf $(whoami)@$(hostname)$ )"
  1165. fi
  1166. ###################################
  1167. # set header and titles
  1168. __my_set_header_line(){
  1169. # save current position
  1170. printf "\033[s"
  1171. # move to 0,0
  1172. printf "\033[0;0H"
  1173. # clear curent to eol
  1174. printf "\033[K"
  1175. # inverse color
  1176. printf "\033[7m"
  1177. printf "$1"
  1178. # restore color
  1179. printf "\033[0m"
  1180. # restore saved position
  1181. printf "\033[u"
  1182. }
  1183. __my_set_screen_name(){
  1184. # set window name
  1185. if test -n "$TMUX" && test -z "$INSIDE_EMACS"
  1186. then
  1187. echo -ne "\033k$1\033\\"
  1188. fi
  1189. }
  1190. __my_set_title(){
  1191. case $TERM in
  1192. (rxvt*|xterm*|aterm|screen*)
  1193. test -t 1 &&
  1194. test -z "$EMACS" &&
  1195. echo -n -e "\033]0;$1\007"
  1196. ;;
  1197. esac
  1198. }
  1199. if test -n "$TMUX"
  1200. then
  1201. # running tmux locally
  1202. __terminal_title="\$(basename \${PWD})"
  1203. elif test -n "$SSH_CONNECTION" && expr "$TERM" : '^screen' >/dev/null
  1204. then
  1205. # ssh connect from tmux terminal
  1206. __terminal_title="`whoami`@`hostname`:\$(basename \${PWD})"
  1207. else
  1208. __terminal_title="`whoami`@`hostname`:\${PWD}"
  1209. fi
  1210. if $inzsh
  1211. then
  1212. precmd(){
  1213. laststatus=$?
  1214. eval __my_set_title ${__terminal_title}
  1215. }
  1216. else
  1217. PROMPT_COMMAND="laststatus=\$?;__my_set_title \"${__terminal_title}\";$PROMPT_COMMAND"
  1218. fi
  1219. laststatus=0