various updates
[distro-setup] / .bashrc
diff --git a/.bashrc b/.bashrc
index ae0da0ae4d11bce5a50a3cde6c35899179571c02..fcaa4b6e033bc23840692a30b15d03a6269deaf2 100644 (file)
--- a/.bashrc
+++ b/.bashrc
@@ -9,17 +9,24 @@
 # Normally, this file is not sourced when a script is run, and it would be much
 # better and more consistent if that also happened when when running a script
 # over ssh. so here we test for conditions of a script under ssh and return if
-# so.  we can override with ssh -t which sets $SSH_TTY, which we can detect
+# so. we can override with ssh -t which sets $SSH_TTY, which we can detect
+# But inside a script, ssh -t won't work, because we aren't using a tty at all.
+# So we need something else. Command lines and env variables sent across ssh are strictly limited.
+# We could override an obscure unused LC_var, like telephone, or we could transfer a file.
+# But I choose to set SendEnv and AcceptEnv ssh vars for BASH_LOGIN_SHELL.
+# In a private file, i have aliases for if $- == *i*, ssh -t, else ssh.
+
+[[ $- != *i* && ! $SSH_CONNECTION ]] && export BASH_LOGIN_SHELL=true
+
 if [[ $SSH_CONNECTION ]] \
    && [[ $- == *c* ]] \
    && [[ ! $SSH_TTY ]] \
+   && [[ ! $BASH_LOGIN_SHELL == true ]] \
    && [[ $- != *i* ]]; then
     return
 fi
 
-# Side note on ssh. Command lines and env variables sent across ssh are strictly limited.
-# If we did want to easily pass info, we could override an obscure unused LC_var
-# Or we could set SendEnv and AcceptEnv ssh vars, or we could transfer a file.
+# Side note on ssh.
 
 
 
@@ -47,31 +54,32 @@ CDPATH=.:/a
 # there is probably a more proper way, but I didn't find any easily on google
 unset GNOME_KEYRING_CONTROL
 
-path_add /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
-
 #use extra globing features. See man bash, search extglob.
 shopt -s extglob
 #include .files when globbing.
 shopt -s dotglob
+#but ignore files name . and ..
+#those are default when this is set to anything, so we just set it to one of them
+export GLOBIGNORE=.
 
-# disabled because it is broken with bash_completion package. It is a known bug they hope to fix.
-# When a glob expands to nothing, make it an empty string instead of the literal characters.
-# shopt -s nullglob
+# broken with bash_completion package. Saw a bug for this once. Don't anymore.
+# still broken in wheezy
+# still buggered in latest stable from the web, version 2.1
+# perhaps its fixed in newer git version, which fails to make for me
+# this note is from 6-2014
+#shopt -s nullglob
 
 # make tab on an empty line do nothing
 shopt -s no_empty_cmd_completion
 
-
 # advanced completion
 # http://bash-completion.alioth.debian.org/
-# i was using the git version for a while for a bug fix.
-# it's made it into distros now
-# usually this is sourced by the system already,
-# but I check just incase
+# might be sourced by the system already, but I've noticed it not being sourced before
 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
     . /usr/share/bash-completion/bash_completion
 fi
 
+
 # fix spelling errors for cd, only in interactive shell
 shopt -s cdspell
 # append history instead of overwritting it
@@ -80,6 +88,8 @@ shopt -s histappend
 shopt -s checkwinsize
 # attempt to save multiline single commands as single history entries.
 shopt -s cmdhist
+shopt -s globstar
+
 
 # inside emacs fixes
 if [[ $INSIDE_EMACS ]]; then
@@ -88,10 +98,6 @@ if [[ $INSIDE_EMACS ]]; then
     export MANPAGER=cat
     # for readline-complete.el
     stty echo
-else
-    # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
-    # gnome-terminal, overridden by bash, or disabled by the system
-    stty werase undef lnext undef stop undef start undef
 fi
 
 
@@ -110,6 +116,10 @@ if [[ $- == *i* ]]; then
             bind '"\eOc": shell-forward-word'
             bind '"\eOd": shell-backward-word'
         fi
+        # terminal keys: C-c, C-z. the rest defined by stty -a are, at least in
+        # gnome-terminal, overridden by bash, or disabled by the system
+        stty werase undef lnext undef stop undef start undef
+
     fi
 
 fi
@@ -139,7 +149,7 @@ unset HISTIGNORE
 
 export BC_LINE_LENGTH=0
 
-path_add /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
+path_add --ifexists /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
 path_add $HOME/bin/bash-programs-by-ian/utils
 # note, if I use a machine I don't want files readable by all users, set
 # umask 077  # If fewer than 4 digits are entered, leading zeros are assumed
@@ -172,7 +182,7 @@ mkdir() {
 alias d='builtin bg'
 complete -A stopped -P '"%' -S '"' d
 
-alias his='history'
+alias hi='history'
 
 
 # note: gksudo is recommended for X apps because it does not set the
@@ -209,7 +219,29 @@ fi
 ###  functions   ####
 #####################
 
-
+# netselect-apt finds a fast mirror.
+# but we need to replace the mirrors ourselves,
+# because it doesn't do that. best it can do is
+# output a basic sources file
+# here we get the server it found, get the main server we use
+# then substitute all instances of one for the other in the sources file
+# and backup original to /etc/apt/sources.list-original.
+# this is idempotent
+debian_pick_mirror () {
+    local x=$(mktemp -d)/f # safe way to get file name without creating one
+    sudo netselect-apt -o $x || return 1
+    x=$(_debian_pick_mirror_grep stable $x)
+    sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
+    sudo sed -i "s/$(_debian_pick_mirror_grep wheezy)/$x/" /etc/apt/sources.list
+}
+
+_debian_pick_mirror_grep () {
+    local x="$(grep -oP "^deb [^ ]+ $1 " ${2-/etc/apt/sources.list})"
+    x="${x#deb }"
+    x="${x% $1 }"
+    # replace / with \/ so we can use it with sed
+    echo "${x//\//\\/}"
+}
 
 a() {
     beet "${@}"
@@ -362,6 +394,10 @@ i() {
 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
     || complete -o default -o nospace -F _git i
 
+# fast commit
+ic() {
+    git commit -am "$*"
+}
 
 # insensitive find
 ifn () {
@@ -370,6 +406,7 @@ ifn () {
 
 
 
+
 l() {
     if [[ $PWD == /[iap] ]]; then
        command ls -A --color=auto -I lost+found "$@"
@@ -422,38 +459,6 @@ despace() {
     done
 }
 
-# force symbolic link creation.
-# trash-put any existing files where links would be created.
-# mkdir -p the directory containing the link(s) if needed.
-# then do ln -s -- "$@"
-lnf() {
-    if [[ $# -gt 2 && ! -d ${!#} ]]; then
-        mkdir -p "${!#}"
-    fi
-    if [[ $# -gt 1 && -d ${!#} ]]; then
-        local oldcwd=$PWD
-        cd ${!#} # last arg
-        for x in "${@:1:$(($#-1))}"; do # all but last arg
-            # remove any trailing slashes
-            x="${x%%+(/)}"
-            # remove any leading directory components
-            x="${x##*/}"
-            te "$x" && trash-put "$x"
-        done
-        cd "$oldcwd"
-    elif [[ $# -eq 2 ]]; then
-        if te "$2"; then
-            trash-put "$2"
-        elif [[ ! -d $(getdir "$2") ]]; then
-            mkdir -p $(getdir "$2")
-        fi
-    else
-        te "${1##*/}" && rm "${1##*/}"
-    fi
-    ln -s -- "$@"
-}
-
-
 
 # package manager
 # aliases would be much more compact, but they can't be used as ssh commands
@@ -497,10 +502,16 @@ else
         fi
     }
     pf() {
+        # scratch a very annoying itch.
+        # package description width as wide as the screen, and package name field small
+        # aptitude manual can't figure out how wide emacs terminal is,
+        # of course it doesn't consult the $COLUMNS variable...
+        # and in a normal terminal, it makes the package name field ridiculously big
+        # also, remove that useless dash before the description
         if [[ $EUID == 0 ]]; then
-            aptitude search "$@"
+            aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
         else
-            sudo aptitude search "$@"
+            sudo aptitude -F "%c%a%M %p %$((COLUMNS - 30))d" -w $COLUMNS search "$@"
         fi
     }
 fi
@@ -563,7 +574,30 @@ q() { # start / launch a program in the backround and redir output to null
 
 
 r() {
-    exit "$@"
+    exit "$@" 2>/dev/null
+}
+
+# trash-restore lists everything that has been trashed at or below CWD
+# This picks out files just in CWD, not subdirectories,
+# which also match grep $1, usually use $1 for a time string
+# which you get from running restore-trash once first
+pick-trash() {
+    local name x ask
+    local nth=1
+    # last condition is to not ask again for ones we skipped
+    while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
+          && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
+        name="$(echo "$name" | head -n $nth | tail -n 1 )"
+        read -p "$name [Y/n] " ask
+        if [[ ! $ask || $ask == [Yy] ]]; then
+            x=$( echo "$name"  | gr -o "^\s*[0-9]*" )
+            echo $x | restore-trash > /dev/null
+        elif [[ $ask == [Nn] ]]; then
+            nth=$((nth+1))
+        else
+            return
+        fi
+    done
 }
 
 # rsync, root is required to keep permissions right.
@@ -589,7 +623,7 @@ complete -F _root_command s sb
 
 # use -ll, less secure but faster.
 srm () {
-    srm -ll "$@"
+    command srm -ll "$@"
 }
 
 # sudo redo. be aware, this command may not work right on strange distros or earlier software
@@ -634,7 +668,7 @@ splay() { # script replay
 
 # timer in minutes
 tm() {
-    (sleep $(calc "$@ * 60") && mpv /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
+    (sleep $(calc "$@ * 60") && mpv --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
 }
 
 
@@ -717,17 +751,18 @@ complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
 
 
 hl() { # history limit. Write extra history to archive file.
-    local max_lines linecount tempfile
+    local max_lines linecount tempfile prune_lines
     local harchive="${HISTFILE}_archive"
     for x in "$HISTFILE" "$harchive"; do
-        if [[ ! $x || ! -w $x || $(stat -c "%u" "$x") != $EUID  ]]; then
-            echo "error in hl: history file $x no good."
+        [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
+        if  [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID  ]];  then
+            echo "error in hl: history file \$x:$x no good"
            return 1
         fi
     done
-    history -w
+    history -a # save history
     max_lines=$HISTFILELINES
-    [[ $max_lines ]] || { echo "error in hl: failed to get max line count"; return 1; }
+    [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
     linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
     [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
     if (($linecount > $max_lines)); then
@@ -737,8 +772,10 @@ hl() { # history limit. Write extra history to archive file.
     fi
 }
 
-# commands to run when bash exits normally
-trap "hl; smh" EXIT
+if [[ $- == *i* ]]; then
+    # commands to run when bash exits normally
+    trap "hl; smh" EXIT
+fi
 
 
 # temporary variables to test colorization
@@ -830,18 +867,15 @@ if [[ $- == *i* ]]; then
     fi
 
     # this needs to come before next ps1 stuff
-    if [[ $BASH_VERSION == [456789]* ]]; then
-        shopt -s autocd
-        shopt -s globstar
-        shopt -s dirspell
-        PS1='\w'
-        if [[ $- == *i* ]]  && [[ ! $INSIDE_EMACS ]]; then
-            PROMPT_DIRTRIM=2
-           bind -m vi-command B:shell-backward-word
-           bind -m vi-command W:shell-forward-word
-        fi
-    else
-        PS1='\W'
+    # this stuff needs bash 4, feb 2009,
+    # old enough to no longer condition on $BASH_VERSION anymore
+    shopt -s autocd
+    shopt -s dirspell
+    PS1='\w'
+    if [[ $- == *i* ]]  && [[ ! $INSIDE_EMACS ]]; then
+        PROMPT_DIRTRIM=2
+       bind -m vi-command B:shell-backward-word
+       bind -m vi-command W:shell-forward-word
     fi
 
     if [[ $SSH_CLIENT ]]; then
@@ -870,10 +904,10 @@ if [[ $- == *i* ]]; then
                ps_char='\$'
                ;;
            1) ps_color="$(get_term_color green)"
-               ps_char=$return
+               ps_char="$return \\$"
                ;;
            *) ps_color="$(get_term_color yellow)"
-               ps_char=$return
+               ps_char="$return \\$"
                ;;
         esac
         if [[ ! -O . ]]; then # not owner
@@ -883,7 +917,7 @@ if [[ $- == *i* ]]; then
                ps_color="$(get_term_color bold green)"
             fi
         fi
-        PS1="${PS1/%!(*[wW]*)}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
+        PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
     }
     PROMPT_COMMAND=prompt_command
 fi