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.
 
 
 
 
 
 

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