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.
 
 
 
 
 
 

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