21 March 2011

When middle click doesn't work in Vim

I mean the Linux feature to use mouse middle click to paste selected text. In vim(not gvim) it sometimes doesn't work. Here I post how to fix it.

In ~/.vimrc find line like
set mouse=a
and change it to
set mouse=r

That's it!

20 March 2011

RPM for nethogs in openSUSE

Nethogs is a 'top' for network connections. It seems, RPMs are no longer supported(At least homepage links for RPM don't work). I had some troubles making an RPM for in in openSUSE. So I'd share a workaround for it.

Download lastest(for now) release tarball and uncompress it:
$ cd /tmp && wget 'http://sourceforge.net/projects/nethogs/files/nethogs/0.7/nethogs-0.7.0.tar.gz/download'
$ tar -xzvf nethogs-0.7.0.tar.gz

Now make
$ cd nethogs
$ make
You may try running
$ sudo checkinstall -R
but if you are at openSUSE box as me, you'd probably get error that says you didn't specify filename in
'install -d -m 755'... If so, edit ./Makefile:
1) find line:
sbin  := $(DESTDIR)/sbin
2) append the folliwing line after that:
bin  := $(DESTDIR)/bin

That's it! Yoy may now run
$ sudo checkinstall -R 
and follow checkinstall instuctions. Everything should be OK now.

Good luck.

UPDATE
You might have to install checkinstall:

$ sudo zipper in checkinstall

Create RPM from source in openSUSE easily. Checkinstall

Being new to openSUSE, I searched for a took "like" checkinstall in Debian. But
openSUSE already has it! :) I'll show how to use it.

Firstly, install it:
$ sudo zypper in checkinstall

Now the whole process mainly looks like the following.

$ ./configure && make
######################################################################
# or 
# qmake 
# or whatever appopriate before doing make install.
######################################################################
$ sudo /usr/sbin/checkinstall
######################################################################
# ... checkinstall advices some settings
######################################################################
$ rpm -i /path/to/generated/rpm
Now let's build an RPM for KeePassX password manager:
$ cd /tmp
$ mkdir keepasx
$ cd keepasx
$ svn co https://keepassx.svn.sourceforge.net/svnroot/keepassx/trunk
$ cd trunk
$ qmake

######################################################################
# To install qmake:
# $ sudo zypper in libqt4-devel
######################################################################
$ sudo /usr/sbin/checkinstall
######################################################################
# Now I had some problems with uncreated directories... Had to issue:
# $ sudo mkdir /usr/share/keepassx /usr/share/mimelnk
# and repeat 
# $ sudo /usr/sbin/checkinstall
######################################################################

Now checkinstall should generate file like
$ /usr/src/packages/RPMS/x86_64/keepassx-0.4.3-1.x86_64.rpm
So may now install the RPM normally:
$ sudo rpm -i /usr/src/packages/RPMS/x86_64/keepassx-0.4.3-1.x86_64.rpm

14 March 2011

How to enable color prompt in byobu

Byobu sets $TERM environment variable to screen-bce, screen.linux, or something beginning with screen(at least currently in Ubuntu 10.10). And if you have your bash prompt normally colorized, it probably won't work in byobu without some changes in ~/.bashrc.

To enable color prompt in boybu find out what's the value of $TERM within byobu:
$ echo $TERM
screen-bce
Now in ~/.bashrc find lines like
# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm*) color_prompt=yes;;
and append the following line there:
    screen*) color_prompt=yes;;
Then find lines like:
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
and change them to:
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*|screen*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"

Here is my ~/.bashrc:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

# don't put duplicate lines in the history. See bash(1) for more options
# don't overwrite GNU Midnight Commander's setting of `ignorespace'.
#export HISTCONTROL=$HISTCONTROL${HISTCONTROL+,}ignoredups
# ... or force ignoredups and ignorespace
export HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
export HISTSIZE=1000
export HISTFILESIZE=3000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm*) color_prompt=yes;;
    screen*) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
 # We have color support; assume it's compliant with Ecma-48
 # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
 # a case would tend to support setf rather than setaf.)
 color_prompt=yes
    else
 color_prompt=
    fi
fi
if [[ "$color_prompt" = yes && "$USER" = root ]]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]: \[\033[01;34m\]\w\[\033[00m\] \$ '
elif [[ "$color_prompt" = yes ]]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[00;33m\]\u@\h\[\033[00m\]: \[\033[01;34m\]\w\[\033[00m\] \$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w \$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*|screen*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# Alias definitions.
if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
fi

export EDITOR='vim'
export GREP_COLOR=';33'
#export PATH=$PATH:/usr/local/mysql/bin:/usr/local/mysql/sbin

11 March 2011

Change wallpaper periodically in Ubuntu

Thanks to UbuntuForums.org, I made a simple cron job changing desktop wallpaper depending on time.

crontab

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
@hourly /share/scripts/bash/change_wallpaper.sh

change_wallpaper.sh

#!/bin/bash -
# Get the pid of nautilus
nautilus_pid=$(pgrep -u $LOGNAME -n nautilus)
# If nautilus isn't running, just exit silently
if [ -z "$nautilus_pid" ]; then
    exit 0
fi
# Grab the DBUS_SESSION_BUS_ADDRESS variable from nautilus's environment
eval $(tr '\0' '\n' < /proc/$nautilus_pid/environ | grep '^DBUS_SESSION_BUS_ADDRESS=')
# Check that we actually found it
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
    echo "Failed to find bus address" >&2
    exit 1
fi
# export it so that child processes will inherit it
export DBUS_SESSION_BUS_ADDRESS
HOUR=$(date +%H)
PICDIR="/usr/share/backgrounds/"
#echo "HOUR: $HOUR"
#echo "PICDIR: $PICDIR"
case $HOUR in
21|22|23|00|01|02|03|04|05|06)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"NATURE-ZenLizard.png"
;;
12|13|14|15|16|17|18|19|20)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"Fern_by_aalex04.jpg" 
;;
09|10|11)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"Bon-Echo_wallpaper.jpg"
;;
*)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"Ropey_Photo_by_Bob_Farrell.jpg"
;;
esac

I wonder, why it didn't work without DBUS_SESSION_BUS_ADDRESS detection. However, it works now. I'd be glad, if it helps someone.

10 March 2011

Simple CLI tool to escape HTML entities

Following scripts read content from stdin and output html-escaped string.

PHP

#!/usr/bin/env php
<?php
/* htmlescape.php */
echo str_replace("\n", "<br />\n", htmlspecialchars( file_get_contents('php://stdin')));
?>

Python

#!/usr/bin/python
# htmlescape.py
import cgi, sys
print cgi.escape(sys.stdin.read())

Usage

$ php htmlescape.php < file.html
or
$ python htmlescape.py < file.html
or for executables:
$ cat file.html | htmlescape.py
$ cat file.html | htmlescape.php
It also works like that:
$ ./htmlescape.py 
if (a > b && c < d) func();                                       
^D
if (a &gt; b &amp;&amp; c &lt; d) func();
^D is Ctrl+D shortcut.
I used it in writing this blog ;)

09 March 2011

Copy SVN working copy changes to a folder

To copy changed files and folders to a temporary folder, I use the following bash script:
#!/bin/bash - 
# FILE: cpsvnst.sh
# USAGE: ./cpsvnst.sh source_dir destination_dir
# DESCRIPTION: Copy changed files and folders from SVN working copy to a temp. dir.
# AUTHOR: Ruslan Osmanov
# CREATED: 11/25/2010 01:37:18 PM UZT

set -o nounset # Treat unset variables as an error

# Displays the message, usage info and exits with error code 1
function my_usage()
{
msg=$1
[[ $msg ]] && echo $msg
echo "Usage:
./$0 source_dir destination_dir
source_dir Source directory
destination_dir Destination directory"
exit 1
}

# Returns dir name with trailing slash
function my_get_dirname()
{
dir=$1
if [[ ${dir:${#dir}-1:1} != '/' ]]; then
dir=$dir"/"
fi
echo $dir
}

src_dir=`my_get_dirname $1`
dst_dir=`my_get_dirname $2`
verbose=1

# Validate args
if [[ ! -d $src_dir ]]; then
usage "'$src_dir' is not a directory"
elif [[ ! -d $dst_dir ]]; then
usage "'$dst_dir' is not a directory"
fi

# Remember current dir
dir=`pwd`
cd $src_dir

# Loop through files and folders
svn st | awk '{ print $2 }' | while read F
do
if [[ $F != 'framework' ]]; then
# Create directory, if not exists
d=`dirname "$dst_dir$F"`
if [[ ! -d $d ]]; then
mkdir -p "$d"
fi

# Copy file or directory
if [[ -f $F ]]; then
[[ $verbose = 1 ]] && echo "FILE $F"
cp -f "$F" "$dst_dir$F"
elif [[ -d $F ]]; then
[[ $verbose = 1 ]] && echo "DIR $F"
[[ ! -d "$dst_dir$F" ]] && mkdir -p "$dst_dir$F"
cp -rf $F $dst_dir$F/../
fi
fi
done

# Go to the initial dir
cd $dir
I'd be glad, if it helped someone.

Snippets in Vim

For common programming snippets in Vim install snipMate plugin.

SnipMate supports autoit, cpp, c, html, javascript, java, mako, objc, perl, php, python, ruby, sh, _, snippet, tcl, tex, vim and zsh file types by default. Default completion is <tab> key. I found it useful to change <tab> to ex. Ctrl+J:
in ~/.vim/after/plugin/snipMate.vim changed
ino <silent> <tab> <c-r>=TriggerSnippet()<cr>
snor <silent> <tab> <esc>i<right><c-r>=TriggerSnippet()<cr>
to
ino <c-j> <c-r>=TriggerSnippet()<cr>
snor <c-j> <esc>i<right><c-r>=TriggerSnippet()<cr>
To use multiple filetypes(as well, as corresponding snippets), you can use whether autoCmd in ~/.vimrc like:
au BufRead *.php set ft=php.html
au BufNewFile *.php set ft=php.html
or modeline like:
/* vim: set ft=html.php: */

Really nice plug-in with intellectual features. E.g. in an HTML file you type:
doctype<c-j>
,
and it suggests to choose one of 7 DOCTYPEs:
HTML 4.01 Strict
HTML 4.01 Transitional
HTML 5
XHTML 1.0 Frameset 
etc.


Enjoy!

UPDATE
Some extra snippets could be found here.

To create your own snippet clone a .snippet file in ~/.vim/snippets/ and modify it on your needs. For instance, I've created this one:

$ cat ~/.vim/snippets/sql/s3_localized.snippet
INSERT INTO \`s3_localized\` (\`localized_code\`) VALUES ('${1:SOMETHING}'); 
SET @ins_id:=(SELECT LAST_INSERT_ID());
INSERT INTO \`s3_localized_text\` (\`localized_id\`, \`lang_id\`, \`localized_text\`)
VALUES 
(@ins_id, 1, '${2:rus}'),
(@ins_id, 2, '${3:eng}'),
(@ins_id, 3, '$3'),
(@ins_id, 4, '$3'),
(@ins_id, 5, '$3'),
(@ins_id, 6, '$3'),
(@ins_id, 7, '$3');

It generates
INSERT INTO `s3_localized` (`localized_code`) VALUES ('SOMETHING'); 
SET @ins_id:=(SELECT LAST_INSERT_ID());
INSERT INTO `s3_localized_text` (`localized_id`, `lang_id`, `localized_text`)
VALUES 
(@ins_id, 1, 'rus'),
(@ins_id, 2, 'eng'),
(@ins_id, 3, 'eng'),
(@ins_id, 4, 'eng'),
(@ins_id, 5, 'eng'),
(@ins_id, 6, 'eng'),
(@ins_id, 7, 'eng');

Ctrl+J moves to the next variable declared in snippet. $-references allow change repeated strings simultaneously(as 'eng' above)

Cyrillic-to-English key mapping in Vim and Vimperator

To avoid switching between keyboard layouts in navigation, visual mode etc. within a mixed Cyrillic/English text append the following to your ~/.vimrc:

set langmap=ФИСВУАПРШОЛДЬТЩЗЙКЫЕГМЦЧНЯ;ABCDEFGHIJKLMNOPQRSTUVWXYZ,фисвуапршолдьтщзйкыегмцчня;abcdefghijklmnopqrstuvwxyz
Similar mapping works for Vimperator. If you use Vimperator, append the following whether to ~/.vimperatorrc, or ~/.vimperatorrc.local(where appropriate):

map пе gt
map пЕ gT

map Ф A
map И B
map С C
map В D
map У E
map А F
map П G
map Р H
map Ш I
map О J
map Л K
map Д L
map Ь M
map Т N
map Щ O
map З P
map Й Q
map К R
map Ы S
map Е T
map Г U
map М V
map Ц W
map Ч X
map Н Y
map Я Z
map ф a
map и b
map с c
map в d
map у e
map а f
map п g
map р h
map ш i
map о j
map л k
map д l
map ь m
map т n
map щ o
map з p
map й q
map к r
map ы s
map е t
map г u
map м v
map ц w
map ч x
map н y
map я z