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.
 
 
 
 
 
 

1409 regels
33 KiB

  1. #!/bin/sh
  2. # TODO: decide the naming scheme of variables (global, local, ...)
  3. expr "$-" : '^.*i' >/dev/null || return
  4. ##########################################
  5. __shrc_lock=/tmp/shrc_lock.$USER.$$
  6. test -f "$__shrc_lock" && return
  7. touch "$__shrc_lock"
  8. ##########################################
  9. null(){
  10. "$@" >/dev/null 2>&1
  11. }
  12. __safe_run(){
  13. type $1 >/dev/null 2>&1 && "$@"
  14. }
  15. __match(){
  16. # __match str word
  17. # return 0 if word is found in str
  18. expr "$1" : ".*$2.*" >/dev/null
  19. }
  20. __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. dfmt="" # actual format for date command
  484. while test -n "$1"
  485. do
  486. fmt="$1"
  487. shift
  488. while test -n "$fmt"
  489. do
  490. case "$fmt" in
  491. YYYY*|yyyy*) # year
  492. dfmt="${dfmt}%Y"
  493. fmt="`echo "$fmt" | cut -c 5-`"
  494. ;;
  495. YY*|yy*) # last two digits of year
  496. dfmt="${dfmt}%y"
  497. fmt="`echo "$fmt" | cut -c 3-`"
  498. ;;
  499. MM*) # month (01..12)
  500. dfmt="${dfmt}%m"
  501. fmt="`echo "$fmt" | cut -c 3-`"
  502. ;;
  503. DD*|dd*) # day of month (01..12)
  504. dfmt="${dfmt}%d"
  505. fmt="`echo "$fmt" | cut -c 3-`"
  506. ;;
  507. HH* | hh*) # hour (00..23)
  508. dfmt="${dfmt}%H"
  509. fmt="`echo "$fmt" | cut -c 3-`"
  510. ;;
  511. mm*) # minute (00..59)
  512. dfmt="${dfmt}%M"
  513. fmt="`echo "$fmt" | cut -c 3-`"
  514. ;;
  515. SS*|ss*) # second (00..60)
  516. dfmt="${dfmt}%S"
  517. fmt="`echo "$fmt" | cut -c 3-`"
  518. ;;
  519. *)
  520. char=`echo "$fmt" | cut -c 1`
  521. dfmt="${dfmt}${char}"
  522. fmt="`echo "$fmt" | cut -c 2-`"
  523. ;;
  524. esac
  525. done
  526. done
  527. date +"$dfmt"
  528. }
  529. # ssh(){
  530. # # __my_terminal_title ssh
  531. # command ssh "$@"
  532. # }
  533. __ssh_with_cd(){
  534. # __ssh_with_cd <host> <directory> [<arg> ...]
  535. if test -z "$2"
  536. then
  537. echo "usage: __ssh_with_cd <host> <directory> [<arg> ...]"
  538. return 1
  539. fi
  540. host="$1"
  541. shift
  542. dir="$1"
  543. shift
  544. ssh "$host" "$@" -t "cd \"$dir\"; \$SHELL -l"
  545. }
  546. memo(){
  547. if test -z "$1"
  548. then
  549. _memo="memo.txt"
  550. else
  551. _memo="$1/memo.txt"
  552. fi
  553. $EDITOR "$_memo"
  554. if test -z "`cat "$_memo"`"
  555. then
  556. echo "$_memo is empty. Removing."
  557. rm "$_memo"
  558. fi
  559. }
  560. now(){
  561. ___tformat="%Y/%m/%d %H:%M:%S %z"
  562. cal
  563. REPLY=
  564. printf "\\r`date "+${___tformat}"`"
  565. read -t 1
  566. while test $? -ne 0
  567. do
  568. printf "\\r`date "+${___tformat}"`"
  569. read -t 1
  570. done
  571. }
  572. s(){
  573. if git rev-parse --git-dir >/dev/null 2>&1
  574. then
  575. echo ">> git grep -n $@" 1>&2
  576. git grep -n "$@"
  577. elif which ag >/dev/null 2>&1
  578. then
  579. echo ">> ag --pager=\"$PAGER\" $@" 1>&2
  580. ag --pager="$PAGER" "$@"
  581. elif which ack >/dev/null 2>&1
  582. then
  583. echo ">> ack --pager=\"$PAGER\" $@" 1>&2
  584. ack --pager="$PAGER" "$@"
  585. else
  586. echo \
  587. ">> find . " \
  588. "-path '*/.git' -prune -o" \
  589. "-path '*/.svn' -prune -o" \
  590. "-type f -exec grep -nH -e --color=always $@ {} +" 1>&2
  591. if test $# -eq 0
  592. then
  593. echo "No search word given." 1>&2
  594. return 1
  595. fi
  596. find . \
  597. -path '*/.git' -prune -o \
  598. -path '*/.svn' -prune -o \
  599. -type -f -exec grep -nH -e --color=always "$@" {} + \
  600. | $PAGER
  601. fi
  602. }
  603. MYMANPATH='/usr/lib/erlang/man'
  604. if $inbash || $inzsh
  605. then
  606. man(){
  607. env \
  608. LESS_TERMCAP_mb=$(printf "\e[1;35m") \
  609. LESS_TERMCAP_md=$(printf "\e[1;31m") \
  610. LESS_TERMCAP_me=$(printf "\e[0m") \
  611. LESS_TERMCAP_se=$(printf "\e[0m") \
  612. LESS_TERMCAP_so=$(printf "\e[1;44;33m") \
  613. LESS_TERMCAP_ue=$(printf "\e[0m") \
  614. LESS_TERMCAP_us=$(printf "\e[1;32m") \
  615. MANPATH="`manpath`:$MYMANPATH" \
  616. man "$@"
  617. }
  618. fi
  619. netwait(){
  620. while ! ping -c 1 -t 1 example.com
  621. do
  622. true
  623. done
  624. echo network works.
  625. }
  626. __realpath(){
  627. if type realpath >/dev/null 2>&1
  628. then
  629. command realpath "$@"
  630. else
  631. while ! test -d $1
  632. do
  633. shift
  634. done
  635. (command cd "$d" && echo "$PWD")
  636. # local d="$OLDPWD"
  637. # command cd "$1"
  638. # echo "$PWD"
  639. # command cd "$d"
  640. fi
  641. }
  642. __safe_alias tmux='env -u SHLVL tmux'
  643. tx(){
  644. tmux start-server
  645. if test -z "$1"
  646. then
  647. echo "usage: tx <session_name>"
  648. tmux list-sessions
  649. elif test -z "$TMUX"
  650. then
  651. # -A: attach if already exists
  652. # tmux new-session -A -c "$HOME" -s "$1"
  653. tmux new-session -A -s "$1"
  654. else
  655. # create new session if not exists yet
  656. # tmux has-session -t "$1" || TMUX= tmux new-session -d -c "$HOME" -s "$1"
  657. tmux has-session -t "$1" || TMUX= tmux new-session -d -s "$1"
  658. tmux switch-client -t "$1"
  659. fi
  660. }
  661. dt(){
  662. # dt [-h] [<name>] [<command ...>]
  663. __dtach_dir="${TMP}/dtach"
  664. mkdir -p "${__dtach_dir}"
  665. if test -n "${__MY_DTACH}"
  666. then
  667. # if already in dtach session print current session
  668. soc_name="`basename "$__MY_DTACH"`"
  669. echo "Current session: ${soc_name}"
  670. fi
  671. if test -z "$1"
  672. then
  673. # if no arg given show list of sessions
  674. echo "Sessions:"
  675. ls "${__dtach_dir}"
  676. return 0
  677. elif test "$1" = "-h"
  678. then
  679. echo "dt: usage: dt [-h] [<name>] [<command ...>]" 1>&2
  680. return 1
  681. fi
  682. # set socket name
  683. soc_name="${__dtach_dir}/$1"
  684. shift
  685. if test -n "$__MY_DTACH"
  686. then
  687. echo "dtach session cannot be nested." 1>&2
  688. return 1
  689. elif test -S "$soc_name"
  690. then
  691. dtach -a "$soc_name" -e ^^
  692. elif test -e "$soc_name"
  693. then
  694. echo "dt: File named $soc_name already exists."
  695. return 1
  696. elif test -z "$1"
  697. then
  698. # if no command given invoke current shell
  699. __MY_DTACH="$soc_name" dtach -c "$soc_name" -e ^^ sh -c "$SHELL"
  700. # echo "dt: Socket named $soc_name not exists and no command specified."
  701. # return 1
  702. else
  703. __MY_DTACH="$soc_name" dtach -c "$soc_name" -e ^^ "$@"
  704. fi
  705. }
  706. scr(){
  707. test -n "$1" && pf="${1}-"
  708. ___tformat="%Y%m%d-%H%M%S%z"
  709. ___file="${HOME}/${pf}`date +${___tformat}`.script"
  710. __MY_SCRIPT=${___file} script ${___file} "$@"
  711. }
  712. dtscr(){
  713. # dtscr <command ...>
  714. if test -z "$1"
  715. then
  716. echo "dtscr: usage: dtscr <command ...>"
  717. return 1
  718. fi
  719. ___cmdstr="`echo $@ | tr ' ' +`"
  720. ___tformat="%Y%m%d-%H%M%S%z"
  721. ___name="${pf}`date +${___tformat}`-${___cmdstr}"
  722. ___scr_file="${HOME}/${___name}.script"
  723. ___dt_dir="${TMP}/dtscr"
  724. mkdir -p "$___dt_dir"
  725. dtach -n "${___dt_dir}/${___name}" script "${___scr_file_}" "$@"
  726. # echo $_name
  727. # echo $_file
  728. }
  729. mcrypt_stream(){
  730. test $# -eq 2 || return 1
  731. case $1 in
  732. en)
  733. mcrypt --key $2 | base64 ;;
  734. de)
  735. base64 -d | mcrypt -d --key $2 ;;
  736. esac
  737. }
  738. gpg_stream(){
  739. test $# -eq 2 || return 1
  740. case $1 in
  741. en)
  742. gpg --passphrase $2 -c --batch |base64 ;;
  743. de)
  744. base64 -d|gpg --passphrase $2 -d --batch ;;
  745. esac
  746. }
  747. dgpg(){
  748. if test "$1" = help || test -z "$2"
  749. then
  750. echo "dgpg: dgpg <en|de> <src-suffix> [<dst-suffix>]" 1>&2
  751. return
  752. fi
  753. ___srcs="$2"
  754. ___dsts="$3"
  755. test -z "$___dsts" && ___dsts="${___srcs}.out"
  756. ___pw=
  757. echo -n "dgpg pw: "
  758. read -s ___pw
  759. echo ""
  760. test -z "$___pw" && return 1
  761. for f in *${___srcs}
  762. do
  763. ___d="$(basename "$f" "${___srcs}")${___dsts}"
  764. echo -n "Processing $f to $___d..."
  765. if test -d "$f"
  766. then
  767. echo "`printf 'failed (%s is directory)' $f`"
  768. elif test -f "$___d"
  769. then
  770. echo "`printf 'failed (%s is already exists)' $___d`"
  771. elif <"$f" gpg_stream $1 $___pw >"$___d" 2>/dev/null
  772. then
  773. echo "done"
  774. else
  775. echo "failed"
  776. test -f "$___d" && rm "$___d"
  777. fi
  778. done
  779. }
  780. alias enst="gpg_stream en"
  781. alias dest="gpg_stream de"
  782. showinfo(){
  783. echo "Japanese letters are 表示可能"
  784. __safe_run diskinfo
  785. ! $isdarwin && test -n "${DISPLAY}" && {
  786. __safe_run xrandr | \grep --color=never ^Screen
  787. }
  788. $iswindows || __safe_run finger $USER
  789. LANG=C __safe_runc id
  790. __safe_run xset q
  791. }
  792. x(){
  793. if [[ -z $DISPLAY ]] && ! [[ -e /tmp/.X11-unix/X0 ]] && (( EUID )); then
  794. #mkdir -p ~/.var/log
  795. # nohup startx >~/.var/log/xorg.log 2>&1 &
  796. # exit
  797. exec startx
  798. else
  799. echo "X cant be started! Another X is already running?" 1>&2
  800. fi
  801. }
  802. bak(){
  803. for file in "$@"
  804. do
  805. cp -v ${file} ${file}.bak
  806. done
  807. }
  808. di(){
  809. if type colordiff >/dev/null 2>&1 && test $TERM != dumb
  810. then
  811. ___diffcmd=colordiff
  812. else
  813. ___diffcmd=diff
  814. fi
  815. ${___diffcmd} -u "$@" | ${PAGER}
  816. }
  817. tb(){
  818. __datenum=`date +%Y%m%d-%H%M%S`
  819. __tb="$HOME/.var/tb/$__datenum"
  820. mkdir -p "$__tb"
  821. mv "$@" "$__tb"
  822. }
  823. mkdd(){
  824. _d=`date +%Y%m%d-%H%M%S` && \
  825. mkdir -p "$_d"
  826. }
  827. mkcd(){
  828. if test -z "$1"
  829. then
  830. echo "mkcd: usage: mkcd <dir>"
  831. return 1
  832. elif test -d "$1"
  833. then
  834. echo "Dir \"$1\" already exists."
  835. else
  836. mkdir -p "$1"
  837. echo "Dir \"$1\" created."
  838. fi
  839. cd "$1"
  840. }
  841. mkcdd(){
  842. # make and change date directory
  843. _d=`date +%Y%m%d-%H%M%S` && \
  844. mkcd "$_d"
  845. }
  846. if test -n "$TMUX" && null type reattach-to-user-namespace
  847. then
  848. alias pbpaste="reattach-to-user-namespace pbpaste"
  849. alias pbcopy="reattach-to-user-namespace pbcopy"
  850. fi
  851. catclip(){
  852. if $iswindows
  853. then
  854. cat /dev/clipboard | tr -d \\r
  855. elif $isdarwin
  856. then
  857. pbpaste
  858. else
  859. xclip -o -selection "clipboard"
  860. fi
  861. }
  862. setclip(){
  863. if test $# -eq 0
  864. then
  865. exec 3<&0
  866. else
  867. exec 3<<__EOF__
  868. `cat "$@"`
  869. __EOF__
  870. fi
  871. if $iswindows
  872. then
  873. 0<&3 sed -e 's/$/\r/' | tee /dev/clipboard
  874. elif $isdarwin
  875. then
  876. pbcopy 0<&3
  877. else
  878. 0<&3 xclip -i -f -selection "primary" | \
  879. xclip -i -f -selection "clipboard"
  880. fi
  881. exec 3<&-
  882. }
  883. open_file(){
  884. if $iscygwin
  885. then
  886. cygstart "$@"
  887. elif $ismsys
  888. then
  889. cmd.exe //c start "" "$@"
  890. elif $isdarwin
  891. then
  892. touch "$@"
  893. open "$@"
  894. elif $islinux
  895. then
  896. touch "$@"
  897. if null type pcmanfm; then
  898. LC_MESSAGES= pcmanfm "$@"
  899. else
  900. LC_MESSAGES= xdg-open "$@" &
  901. fi
  902. else
  903. cat "$@"
  904. fi
  905. }
  906. o(){
  907. if test $# -eq 0
  908. then
  909. open_file .
  910. else
  911. for f in "$@"
  912. do
  913. open_file "$(realpath "$f")"
  914. done
  915. fi
  916. }
  917. convmv_sjis2utf8_test(){
  918. convmv -r -f sjis -t utf8 *
  919. }
  920. convmv_sjis2utf8_notest(){
  921. convmv -r -f sjis -t utf8 * --notest
  922. }
  923. #################################################
  924. ## pastebin services
  925. ## https://wiki.archlinux.org/index.php/List_of_Applications/Internet#Pastebin_clients
  926. sprunge(){
  927. # http://sprunge.us
  928. if test -z "$1"
  929. then
  930. curl -F 'sprunge=<-' http://sprunge.us
  931. else
  932. curl http://sprunge.us/$1
  933. fi
  934. }
  935. dpaste(){
  936. # http://dpaste.de
  937. if test -z "$1"
  938. then
  939. curl -F 'content=<-' https://dpaste.de/api/
  940. echo
  941. else
  942. curl https://dpaste.de/$1/raw/
  943. fi
  944. }
  945. ######################################
  946. ## Prompt Settings
  947. __my_moc_state(){
  948. type mocp >/dev/null 2>&1 || return
  949. test "`mocp -Q %state 2>/dev/null`" = PLAY || return
  950. printf "$1" "`mocp -Q %title 2>/dev/null`"
  951. }
  952. __my_parse_svn_branch() {
  953. ___svn_url=$(LANG=C svn info 2>/dev/null | sed -ne 's#^URL: ##p')
  954. ___svn_repository_root=$(LANG=C svn info 2>/dev/null | \
  955. sed -ne 's#^Repository Root: ##p')
  956. echo ${___svn_url} | sed -e 's#^'"${___svn_repository_root}"'##g' | \
  957. awk '{print $1}'
  958. }
  959. __my_svn_ps1(){
  960. if svn status >/dev/null 2>&1
  961. then
  962. ___svn_branch=$(__my_parse_svn_branch)
  963. test -n "${___svn_branch}" && printf "$1" "{$___svn_branch}"
  964. fi
  965. }
  966. __my_battery_status(){
  967. ___dir=/sys/class/power_supply/BAT0
  968. if test -d $___dir && test -r $___dir/status && test -r $___dir/charge_full && \
  969. test -r $___dir/charge_now
  970. then
  971. ___st=$(cat $___dir/status)
  972. ___full=$(cat $___dir/charge_full)
  973. ___now=$(cat $___dir/charge_now)
  974. ___rate=$(expr $now \* 100 / $full)
  975. printf "$1" "${___st}:${___rate}%"
  976. fi
  977. }
  978. alias bat='__my_battery_status %s\\n'
  979. __my_ps1_scale(){
  980. if null type stty && ! $ismsys
  981. then
  982. echo "[LxC:`stty size | tr -d $'\n' | tr " " x`]"
  983. fi
  984. }
  985. __my_ps1_tmux(){
  986. null type tmux || return $last
  987. ___tmuxc="$(tmux display -p '#S:#I:#W.#P' 2>/dev/null)"
  988. test -n "$TMUX" && echo "[TMUX:$___tmuxc]"
  989. }
  990. __my_ps1_moc(){
  991. __my_moc_state "[MOC:%s]"
  992. }
  993. for f in /usr/share/git/git-prompt.sh \
  994. /usr/share/git-core/contrib/completion/git-prompt.sh \
  995. /usr/local/share/git-core/contrib/completion/git-prompt.sh \
  996. /etc/bash_completion.d/git-prompt \
  997. /opt/local/share/git-core/git-prompt.sh \
  998. /opt/local/share/doc/git-core/contrib/completion/git-prompt.sh
  999. do
  1000. test -r "$f" && ($inbash || $inzsh) && . "$f" && break
  1001. done
  1002. GIT_PS1_SHOWDIRTYSTATE=t
  1003. GIT_PS1_SHOWUPSTREAM=t
  1004. __my_ps1_git(){
  1005. null type __git_ps1 || return $last
  1006. null git rev-parse --git-dir >/dev/null 2>&1 || return $last
  1007. __git_ps1 "[GIT:$(__safe_run git config --get user.name):%s]"
  1008. }
  1009. __printf_ipaddr(){
  1010. # ipaddress <fmt>
  1011. type ip >/dev/null 2>&1 || return 1
  1012. ___ip=$(LANG=C ip addr show scope global | \
  1013. \grep --color=never --only-matching 'inet [^ ]*' | cut -d " " -f 2)
  1014. test -n "$___ip" && printf "$1" $___ip
  1015. }
  1016. alias addr="__printf_ipaddr '%s'"
  1017. __my_ps1_ipaddr(){
  1018. ! $iswindows && __printf_ipaddr '[Addr:%s]'
  1019. }
  1020. __my_ps1_bttry(){
  1021. ___bst="${TMP}/batterystatus"
  1022. if test -z "$DISPLAY" && ! $iswindows
  1023. then
  1024. test -f $___bst && ___bstr="$(cat $___bst)"
  1025. test -n "$___bstr" && ! echo $___bstr | grep 100 >/dev/null 2>&1 && \
  1026. echo "[Battery:$___bstr]"
  1027. __my_battery_status %s >$___bst &
  1028. fi
  1029. }
  1030. __my_ps1_memo(){
  1031. test -f memo.txt && echo "m:`du -b memo.txt|cut -f 1`"
  1032. }
  1033. __my_ps1_dirs(){
  1034. dirs | wc -l
  1035. }
  1036. __my_ps1_jobs(){
  1037. # __my_ps1_jobs [<num>]
  1038. if test -n "$1"
  1039. then
  1040. jobs="$1"
  1041. else
  1042. jobs="`jobs | wc -l`"
  1043. fi
  1044. if test "$jobs" -gt 0
  1045. then
  1046. echo "JOBS:$jobs"
  1047. fi
  1048. }
  1049. __my_ps1_dollar(){
  1050. if test -z "$SHLVL"
  1051. then
  1052. printf "$1"
  1053. else
  1054. perl -e 'while($ARGV[0]-- > 0){print "$ARGV[1]";}' $SHLVL "$1"
  1055. fi
  1056. }
  1057. __my_alert_fail(){
  1058. test $laststatus -eq 0 || \
  1059. echo "STATUS:${laststatus}"
  1060. }
  1061. # About ansi escape sequences
  1062. # http://archive.linux.or.jp/JF/JFdocs/Bash-Prompt-HOWTO-5.html
  1063. # http://www.grapecity.com/japan/powernews/column/clang/047/page02.htm
  1064. if $inbash || $inzsh
  1065. then
  1066. if $inzsh
  1067. then
  1068. __attr_beg=$'%{\033['
  1069. __attr_end='m%}'
  1070. else
  1071. __attr_beg='\[\033['
  1072. __attr_end='m\]'
  1073. fi
  1074. __color_default="${__attr_beg}0${__attr_end}"
  1075. __color_black="${__attr_beg}0;30${__attr_end}"
  1076. __color_red="${__attr_beg}0;31${__attr_end}"
  1077. __color_green="${__attr_beg}0;32${__attr_end}"
  1078. __color_brown="${__attr_beg}0;33${__attr_end}"
  1079. __color_blue="${__attr_beg}0;34${__attr_end}"
  1080. __color_purple="${__attr_beg}0;35${__attr_end}"
  1081. __color_cyan="${__attr_beg}0;36${__attr_end}"
  1082. __color_light_gray="${__attr_beg}0;37${__attr_end}"
  1083. __color_dark_gray="${__attr_beg}1;30${__attr_end}"
  1084. __color_light_red="${__attr_beg}1;31${__attr_end}"
  1085. __color_light_green="${__attr_beg}1;32${__attr_end}"
  1086. __color_yellow="${__attr_beg}1;33${__attr_end}"
  1087. __color_light_blue="${__attr_beg}1;34${__attr_end}"
  1088. __color_light_purple="${__attr_beg}1;35${__attr_end}"
  1089. __color_light_cyan="${__attr_beg}1;36${__attr_end}"
  1090. __color_white="${__attr_beg}1;37${__attr_end}"
  1091. __color_bg_black="${__attr_beg}40${__attr_end}"
  1092. __color_bg_red="${__attr_beg}41${__attr_end}"
  1093. __color_bg_green="${__attr_beg}42${__attr_end}"
  1094. __color_bg_brown="${__attr_beg}43${__attr_end}"
  1095. __color_bg_blue="${__attr_beg}44${__attr_end}"
  1096. __color_bg_purple="${__attr_beg}45${__attr_end}"
  1097. __color_bg_cyan="${__attr_beg}46${__attr_end}"
  1098. __color_bg_light_gray="${__attr_beg}47${__attr_end}"
  1099. __attr_underline="${__attr_beg}4${__attr_end}"
  1100. __attr_reverse="${__attr_beg}7${__attr_end}"
  1101. __attr_bold="${__attr_beg}1${__attr_end}"
  1102. fi
  1103. # NOTE: tput is another easy way to set colors and background
  1104. # For example, "$(tput setab 4)text$(tput sgr0)" print text with background
  1105. # color blue.
  1106. # http://www.ibm.com/developerworks/jp/linux/aix/library/au-learningtput/index.html
  1107. if test "$TERM" != dumb
  1108. then
  1109. __my_c1="$__attr_bold$__attr_underline" # color for PWD
  1110. __my_c2="$__attr_bold$__attr_underline" # color for user and hostname
  1111. # color for ::
  1112. case "`hostname`" in
  1113. arch-aspireone)
  1114. __my_c4="$__color_yellow"
  1115. ;;
  1116. arch-mba)
  1117. __my_c4="$__color_light_cyan"
  1118. ;;
  1119. newkiwi)
  1120. __my_c4="$__color_light_purple"
  1121. ;;
  1122. debian-vb-win7-opti)
  1123. __my_c4="$__color_light_red"
  1124. ;;
  1125. *)
  1126. __my_c4="$__color_light_green"
  1127. ;;
  1128. esac
  1129. __my_c5="$__color_black$__color_bg_light_gray" # color for SCR
  1130. __my_cdef="$__color_default"
  1131. fi
  1132. if $inbash
  1133. then
  1134. __my_ps1_sh="[BASH:$BASH_VERSION]"
  1135. elif $inzsh
  1136. then
  1137. __my_ps1_sh="[ZSH:$ZSH_VERSION]"
  1138. fi
  1139. __my_ps1_info1(){
  1140. # first line of PS1
  1141. echo "${__my_ps1_sh}$(__my_ps1_scale)$(__my_ps1_git)$(__my_ps1_bttry)$(__my_ps1_moc)"
  1142. }
  1143. test -n "$__MY_SCRIPT" && \
  1144. __my_ps1_str_scr="SCR"
  1145. test -n "$SSH_CONNECTION" && \
  1146. __my_ps1_str_ssh="SSH"
  1147. test -n "$__MY_DTACH" && \
  1148. __my_ps1_str_dt="DT:`basename "$__MY_DTACH$"`"
  1149. __my_ps1_info2(){
  1150. # second line of PS1
  1151. echo $(__my_ps1_memo) $(__my_ps1_jobs) ${__my_ps1_str_scr} \
  1152. ${__my_ps1_str_ssh} ${__my_ps1_str_dt} $(__my_alert_fail) \
  1153. | sed -e 's/ /|/g'
  1154. }
  1155. __my_ps1_beg="${__my_c4}:: ${__my_cdef}"
  1156. __my_ps1_save_pos="\[\033[s\]"
  1157. __my_ps1_restore_pos="\[\033[u\]"
  1158. __my_ps1_move_rightmost="\[\033[\$(tput cols)C\]"
  1159. __my_ps1_move_15left="\[\033[15D\]"
  1160. # collapse when command line is too long and try to write over this string
  1161. # __my_ps1_right="${__my_ps1_save_pos}${__my_ps1_move_rightmost}"
  1162. # ${__my_ps1_move_15left}\D{%Y/%m/%d %H:%M}${__my_ps1_restore_pos}
  1163. if $inzsh
  1164. then
  1165. PROMPT="\
  1166. ${__my_ps1_beg}[${__my_c2}%n@%M${__my_cdef}:${__my_c1}%~/${__my_cdef}]\$(__my_ps1_info1)
  1167. ${__my_ps1_beg}\$(__my_ps1_info2) $(__my_ps1_dollar %#) "
  1168. RPROMPT="%D{%Y/%m/%d %H:%M}"
  1169. elif $inbash
  1170. then
  1171. PS1="\
  1172. ${__my_ps1_beg}[${__my_c2}\u@\H${__my_cdef}:${__my_c1}\w/${__my_cdef}]\$(__my_ps1_info1)\n\
  1173. ${__my_ps1_beg}\D{%Y/%m/%d %H:%M} \$(__my_ps1_info2)${__my_ps1_right} $(__my_ps1_dollar \\$) "
  1174. else
  1175. true
  1176. # PS1="$(printf $(whoami)@$(hostname)$ )"
  1177. fi
  1178. ###################################
  1179. # set header and titles
  1180. __my_set_header_line(){
  1181. # save current position
  1182. printf "\033[s"
  1183. # move to 0,0
  1184. printf "\033[0;0H"
  1185. # clear curent to eol
  1186. printf "\033[K"
  1187. # inverse color
  1188. printf "\033[7m"
  1189. printf "$1"
  1190. # restore color
  1191. printf "\033[0m"
  1192. # restore saved position
  1193. printf "\033[u"
  1194. }
  1195. __my_set_screen_name(){
  1196. # set window name
  1197. if test -n "$TMUX" && test -z "$INSIDE_EMACS"
  1198. then
  1199. echo -ne "\033k$1\033\\"
  1200. fi
  1201. }
  1202. __my_set_title(){
  1203. case $TERM in
  1204. (rxvt*|xterm*|aterm|screen*)
  1205. test -t 1 &&
  1206. test -z "$EMACS" &&
  1207. echo -n -e "\033]0;$1\007"
  1208. ;;
  1209. esac
  1210. }
  1211. if test -n "$TMUX"
  1212. then
  1213. # running tmux locally
  1214. __terminal_title="\$(basename \${PWD})"
  1215. elif test -n "$SSH_CONNECTION" && expr "$TERM" : '^screen' >/dev/null
  1216. then
  1217. # ssh connect from tmux terminal
  1218. __terminal_title="`whoami`@`hostname`:\$(basename \${PWD})"
  1219. else
  1220. __terminal_title="`whoami`@`hostname`:\${PWD}"
  1221. fi
  1222. if $inzsh
  1223. then
  1224. precmd(){
  1225. laststatus=$?
  1226. eval __my_set_title ${__terminal_title}
  1227. }
  1228. else
  1229. PROMPT_COMMAND="laststatus=\$?;__my_set_title \"${__terminal_title}\";$PROMPT_COMMAND"
  1230. fi
  1231. laststatus=0