2012/12/25

Reset root password for PostgreSQL

EITHER:

$ ps -ef | grep postgres
postgres  3940     1  0 12:38 ?        00:00:00 /usr/lib/postgresql/8.4/bin/postgres -D /var/lib/postgresql/8.4/main -c config_file=/etc/postgresql/8.4/main/postgresql.conf

$ grep 'hba_file' /etc/postgresql/8.4/main/postgresql.conf
hba_file = '/etc/postgresql/8.4/main/pg_hba.conf' # host-based authentication file

# vi /etc/postgresql/8.4/main/pg_hba.conf

OR:

# vi $(grep 'hba_file' $(ps -ef | grep postgres | awk '{ if ( $3 == 1 ) print $NF }' | cut -d '=' -f 2) | cut -d "'" -f 2)

#local all postgres md5
local all postgres trust

# service postgresql-8.4 restart

# su - postgres

$ psql -d template1 -U postgres

> alter user postgres with password 'new_password';

# vi /etc/postgresql/8.4/main/pg_hba.conf


OR:

# vi $(grep 'hba_file' $(ps -ef | grep postgres | awk '{ if ( $3 == 1 ) print $NF }' | cut -d '=' -f 2) | cut -d "'" -f 2)


local all postgres md5
#local all postgres trust

# service postgresql-8.4 restart

$ psql -d template1 -U postgres

2012/11/08

Efficient splitting every 3 digits

my $num = 12_345_678;
$num = reverse $num;
$num = reverse join( ' ', grep( $_, split( /(...)/g, $num ) ) );
# $num = '12 345 678';

2012/10/31

UTF8

# flags source code as UTF8
use utf8;

# flags STDOUT as UTF8
binmode(STDOUT, ":encoding(utf-8)");

2012/10/23

Stop "sshd" in Ubuntu

Internet says this one works: 
sudo update-rc.d -f sshd remove

but  it isn't.
It does NOT work.
The following works: 
sudo apt-get remove openssh-server

2012/10/18

Real UID vs Effective UID

If you think about a large company where employees have different levels of access to different locations, you could compare the Real User ID to the name badges people wear, and the Effective User ID to the set of keys they've been given.

2012/10/12

Perl module version

perl -MDateTime -le 'print DateTime->VERSION'

OR:

pmvers DateTime

Perl - read in a whole file at once

use Perl6::Slurp;
my $data = slurp 'path/to/file';

OR

use File::Slurp;
my $text = read_file( 'filename' );
my $lines = read_file( 'filename', array_ref => 1 );
my $lines = read_file( 'filename', array_ref => 1, chomp => 1 );

OR

use File::Slurper;

OR

my $body = do { local( @ARGV, $/ ) = $filename; <> };

OR (if the file is under __DATA__)

my $body = join( '', <DATA> );

Permissions

(not optimised for performance, but does the job):

find . -name '.svn' -prune -o -type d -exec chown www-data:www-data {} \;
-exec chmod 700 {} \; -o -type f -exec chown www-data:www-data {} \; -exec chmod 600 {} \;

List all users

List all users:
awk -F: '{ print $1 }' /etc/passwd

List all members of a group:
awk -F: '/^groupname/ {print $4;}' /etc/group

Where is the package in Ubuntu?

dpkg-query -L package
dpkg -l | grep package

Server in colors

.bashrc:

# PS1='\[\e[1;34m\]\u\[\e[0m\]@\[\e[1;31m\]\h:\[\e[1;32m\]\w\[\e[1;34m\]\njobs:\j\[\e[0m\]\$ '

PS1='\[\e[0;37m\][\[\e[1;94m\]\[\e[1;94m\]\u\[\e[0m\]@\[\e[1;31m\]\H: \[\e[1;32m\]\w\[\e[1;94m\]\[\e[0;37m\]]\n\[\e[0m\]\$ '

Brian's Guide to Solving Any Perl Problem

http://www.perlmonks.org/?node_id=376075

INSERT into SELECT from

insert into TABLE1
(field1, field2, field3, field4)
select 'value1', 'value2', field3, field4
from TABLE1 where field5 = 'value5' limit 1;

Exuberant ctags in FreeBSD

1. install exuberant ctags into "somewhere"
2. point "/home/me/bin/ctags" to "somewhere/ctags.exe"
3. run in vim (add to .vimrc):

:filetype plugin on
map <F1> <esc>:TlistToggle<cr>
:let Tlist_Ctags_Cmd='/home/me/bin/ctags'

4. Install Taglist plugin for Vim.
Debianaptitude install exuberant-ctags
Macbrew install ctags-exuberant

2012/10/09

Citates

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live

Perl will protect its internals from your race conditions, but it won't protect you from you

If you feel the urge to shoot yourself in the foot by using multiple inheritance, Perl is not going to stop you

Perl is a language for getting your job done

P is for Practical

2012/09/20

Config modules

Config::Fast
- NOT structured
+ honours whitespace

Config::Std
+ structured
- NOT honours whitespace

Config::Simple
+ structured
+ honours whitespace

Config::General
+ structured
+ honours whitespace
+ vars
- # overrides "

all the above have their own format

Config::JSON
+ structured
+ honours whitespace
- NO vars
+ " overrides #
+ universal

2012/09/11

Vim: search on a single line

commands: "F" (backwards), "f" (forward)
Repeaters: "," (prev), ";" (next)
var = expr . expr . expr
fe;;;

2012/08/16

SOAP via WSDL

#####
/home/michael/localhost/cgi-bin/server.cgi:

#!/usr/bin/env perl

use SOAP::Transport::HTTP;

SOAP::Transport::HTTP::CGI
    -> dispatch_to( '/home/michael/localhost/lib', 'Hi' )
    -> handle;

#####
/home/michael/localhost/lib/Hi.pm:

package Hi;

use base 'SOAP::Server::Parameters';

my $AUTH = {
    'user' => 'admin',
    'pass' => 'temp123',
};

sub hi {
    my ($self, $name) = @_;

    unless ( $ENV{'HTTPS'} ) {
        return 'https only, please';
    }

    unless ( $self->check_auth( pop ) ) {
        return 'Hello, unauthenticated';
    }

    unless ( $name ) {
        $name = 'world';
    }

    return "Hello, $name";
}

sub check_auth {
    my ($self, $envelope) = @_;

    my $header = $envelope->{'_content'}[-3]{'Header'};

    my $authenticated = 0;

    if (
        $header->{'Username'}
        &&
        $header->{'Password'}
        &&
        $header->{'Username'} eq $AUTH->{'user'}
        &&
        $header->{'Password'} eq $AUTH->{'pass'}
    ) {
        $authenticated = 1;
    }

    return $authenticated;
}

#sub debug {
#   use Data::Dumper;
#   my $message = shift;
#   print STDERR Dumper( $message );
#}

1;

#####
/home/michael/localhost/bin/client.pl:

#!/usr/bin/env perl

use SOAP::Lite
    on_fault => sub {
        my ($soap, $res) = @_;
        eval { die ref $res ? $res->faultstring : $soap->transport->status };
        return ref $res ? $res : SOAP::SOM->new();
    };

use Data::Dumper;

my $user = 'admin';
my $pass = 'temp123';

my $header = SOAP::Header
    -> name('Security')
    -> value(
        SOAP::Header
        -> name('UsernameToken')
        -> value(
            SOAP::Header->name('Username' => $user),
            SOAP::Header->name('Password' => $pass),
        ),
    );

my $soap = SOAP::Lite
    -> service('http://192.168.4.46/wsdl');

my $greeting = $soap->hi('York', $header);
print "$greeting\n";

#####
/home/michael/localhost/www/wsdl:

<?xml version="1.0" encoding="UTF-8"?>
<definitions name="Hi"
   targetNamespace="http://192.168.4.46/wsdl"
   xmlns="http://schemas.xmlsoap.org/wsdl/"
   xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
   xmlns:tns="http://192.168.4.46/wsdl"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema">

   <message name="HiRequest">
      <part name="name" type="xsd:string"/>
   </message>
   <message name="HiResponse">
      <part name="greeting" type="xsd:string"/>
   </message>

   <portType name="HiPortType">
      <operation name="hi">
         <input message="tns:HiRequest"/>
         <output message="tns:HiResponse"/>
      </operation>
   </portType>
  
   <binding name="HiBinding" type="tns:HiPortType">
      <soap:binding style="rpc"
         transport="http://schemas.xmlsoap.org/soap/http"/>
      <operation name="hi">
         <soap:operation soapAction="urn:Hi#hi"/>
         <input>
            <soap:body
               encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
               namespace="urn:Hi"
               use="encoded"/>
         </input>
         <output>
            <soap:body
               encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
               namespace="urn:Hi"
               use="encoded"/>
         </output>
      </operation>
   </binding>

   <service name="HiService">
      <documentation>WSDL File for HiService</documentation>
      <port binding="tns:HiBinding" name="HiPort">
         <soap:address
            location="https://192.168.4.46/cgi-bin/server.cgi"/>
      </port>
   </service>
</definitions>

2012/08/13

SOAP

cgi-bin/server.cgi:

#!/usr/bin/env perl

use SOAP::Transport::HTTP;

SOAP::Transport::HTTP::CGI
    ->dispatch_to('/home/michael/localhost/lib', 'Demo')
    ->handle;

lib/Demo.pm:

package Demo;

sub hi {
    return 'Hello, world';
}

sub bye {
    return 'Goodbye, cruel world';
}

1;

somewhere/client.pl:

#!/usr/bin/env perl

use SOAP::Lite;

my $hi = SOAP::Lite
    ->uri('http://localhost/Demo')
    ->proxy('http://localhost/cgi-bin/server.cgi')
    ->hi()
    ->result();

print "hi: [$hi]\n";

my $bye = SOAP::Lite
    ->uri('http://localhost/Demo')
    ->proxy('http://localhost/cgi-bin/server.cgi')
    ->bye()
    ->result();

print "bye: [$bye]\n";


2012/08/09

sub inside sub

bar() is only visible inside foo() and it does not leak
(as opposed to: my $bar = sub {}; $bar->(); but that is not tested -- see "http://www.perlmonks.org/index.pl?node=833941" for explanation)

sub foo {
    print "in foo\n";
    local *bar = sub {
        print "in bar\n";
    };
    bar();
}

foo();

2012/08/03

vim syntax

:set syn=perl
:set syn=cpp
:set syn=javascript

full list:
/usr/share/vim/vim72/syntax

2012/07/24

memoize caveat

Functions that return references to values
that may be modified by their callers must not be memoized.

use Memoize;

sub iota {
    my $n = shift;
    return [1 .. $n];
}

memoize 'iota';

$i10 = iota(10);
$j10 = iota(10);

pop @$i10;

print @$j10;

2012/07/23

Unique values (Perl)

use List::MoreUtils qw( uniq );

@arr = qw( 4 4 2 2 );

@arr = uniq @arr;

print "@arr\n";


# =====
my @uniq = unique( @in );

sub unique
{
    my %seen;
    return grep {!$seen{$_}++} @_;
}

2012/07/20

max len key (Perl6::Form)

my $max_len = max( map { length } keys %{$form} );

#!/usr/bin/perl

use List::Util qw( max );
use Perl6::Form;
use Data::Dumper;

my $form = {
    'name' => 'mike',
    'surname' => 'shmike',
    'region' => 'kiev',
};

my @body;
my $max_len = max( map { length } keys %{$form} ) - 2;
foreach my $key ( keys %{$form} )
{
    push @body, form(
        '{' . ('>' x $max_len) . '}: {' . ('<' x $max_len) . '}',
        $key, $form->{$key},
    );
#   print form(
#       '{' . ('>' x $max_len) . '}: {' . ('<' x $max_len) . '}',
#       $key, $form->{$key},
#   );
}

print Dumper( \@body );

2012/07/06

shrink @arr1 by @arr2

#!/usr/bin/perl

use List::Compare;

my @arr1 = qw( free bsd shmsd );
my @arr2 = qw(          shmsd yo );
my $lc = List::Compare->new( \@arr1, \@arr2 );

# intersection
my @intersection = $lc->get_intersection;
print "@intersection\n";

# union
my @union = $lc->get_union;
print "@union\n";

# outersection
my @outersection = $lc->get_symmetric_difference;
print "@outersection\n";




############
#!/usr/bin/perl

use Data::Dumper;
use List::MoreUtils qw( none );

@arr1 = qw( free bsd shmsd );
@arr2 = qw( shmsd );

# shrink @arr 1 by @arr2
@arr1 = grep {
        my $arr1 = $_;
        none { $_ eq $arr1 } @arr2
} @arr1;

print Dumper( \@arr1 );
( prints [free bsd] )


############
#!/usr/bin/perl

use Data::Dumper;
use List::MoreUtils qw( any );

@arr1 = qw( free bsd shmsd );
@arr2 = qw( shmsd );

# find common between @arr1 and @arr2
@arr1 = grep {
        my $arr1 = $_;
        any { $_ eq $arr1 } @arr2
} @arr1;

print Dumper( \@arr1 );
( prints [shmsd] )

2012/07/03

Remove control characters


:set fileformat=unix

$var =~ s/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]//sg;

2012/07/02

jQuery autocomplete

<script type="text/javascript">

$(function() {

    var cache = {};
    var last_xhr;
  
    $("#search_input").autocomplete({
        minLength: 3,
        source: function (request, response) {
          
            var term = request.term;
          
            if ( term in cache ) {
                response(cache[term]);
                return;
            }
          
            last_xhr = $.getJSON("/server-side/search.php", request, function(data, status, xhr) {
                cache[term] = data;
                if ( xhr === last_xhr ) {
                    response(data);
                }
            });
        }
    }).autocomplete("widget").addClass('ui-search-results');
   
   
    $('#search_input').data("autocomplete")._renderItem = function(ul, item) {
        return createElement(item)
            .data("item.autocomplete", item)
            .appendTo(ul);
    };

});

</script>

2012/06/19

sort array of hashes

#!/usr/bin/perl

use Data::Dumper;

@arr = (
        {
                '10' => '5',
        },
        {
                '30' => '1',
        },
        {
                '20' => '3',
        },
);

@arr_sorted = sort { (values(%$b))[0] <=> (values(%$a))[0] } @arr;


Get a list of hash keys sorted by value:
@sorted_keys = sort { $hash{$a} cmp $hash{$b} } keys %hash;

print Dumper( @arr_sorted );

2012/04/27

mount windows share

/etc/fstab:
//our_share/michael /mnt/my_share smbfs users,rw,noperm,credentials=/etc/samba/cred-file,forceuid=michael,forcegid=admin 0 0

/etc/rc.local:
mount //our_share/michael

2012/04/19

link button

[ a style="display:block; padding: 3px 20px; border: 1px solid #b2b2b2; background: #ccc; text-decoration: none; float: left; color: black; font-size: 14px;" href="" ]

2012/04/13

ENV

DOCUMENT_ROOT: /home/user/localhost
GATEWAY_INTERFACE: CGI/1.1
HTTP_ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_CHARSET: ISO-8859-1,utf-8;q=0.7,*;q=0.7
HTTP_ACCEPT_ENCODING: gzip, deflate
HTTP_ACCEPT_LANGUAGE: en-us,en;q=0.5
HTTP_CACHE_CONTROL: max-age=0
HTTP_CONNECTION: keep-alive
HTTP_HOST: localhost
HTTP_USER_AGENT: Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20100101 Firefox/2.0.1
PATH: /usr/local/bin:/usr/bin:/bin
QUERY_STRING: key=value
REMOTE_ADDR: 127.0.0.1
REMOTE_PORT: 49185
REQUEST_METHOD: GET
REQUEST_URI: /cgi-bin/env.pl?key=value
SCRIPT_FILENAME: /home/user/localhost/cgi-bin/env.pl
SCRIPT_NAME: /cgi-bin/env.pl
SERVER_ADDR: 127.0.0.1
SERVER_ADMIN: webmaster@localhost
SERVER_NAME: localhost
SERVER_PORT: 80
SERVER_PROTOCOL: HTTP/1.1
SERVER_SIGNATURE:
Apache/2.2.20 (Ubuntu) Server at localhost Port 80

SERVER_SOFTWARE: Apache/2.2.20 (Ubuntu)

2012/04/11

matcher

#!/usr/bin/perl

$string = 'abcdefg efgdabcz';

$matched = $string =~ /ab.{2}/g;
($match) = $string =~ /ab.{2}/g;
($match1, $match2) = $string =~ /ab.{2}/g;
@matches = $string =~ /ab.{2}/g;
$count = @matches = $string =~ /ab.{2}/g;

print "matched: [$matched]\n";
print "match: [$match]\n";
print "match1: [$match1], match2: [$match2]\n";
print "matches: [@matches]\n";
print "count: [$count]\n";

2012/04/02

Regex modifiers

/m    (^) ... ($)  \n  (^) ... ($)
/s    (^) ...  $  (\n)  ^  ... ($)
/ms   (^) ... ($) (\n) (^) ... ($)

         (\A) ... \n ... (\Z) \n
         (\A) ... \n ...     (\z)


###
havoc without [ms]:

#!/usr/bin/perl

$str = "abc\ndef\nghi";

print 'NO [m] [s]: ';
if ( $str =~ m/^(\w{1}).*(\w{1})$/ )
{
        print "$1::$2";
}
print "\n";


print '[m]: ';
if ( $str =~ m/^(\w{1}).*(\w{1})$/m )
{
        print "$1::$2";
}
print "\n";


print '[s]: ';
if ( $str =~ m/^(\w{1}).*(\w{1})$/s )
{
        print "$1::$2";
}
print "\n";

# s/// is ok (/s by default)
print "[change]: \n";
$str =~ s/def//;
print "$str\n";

2012/03/26

Search @INC

perldoc -l My::Module

perl -e 'print join " ", @INC, "-name Simple.pm"' | xargs find

perl -e 'print join " ", @INC, "-wholename *Some/Simple.pm"' | xargs find

for inc in $(perl -e 'print join " ", @INC');
do
find $inc -name Simple.pm;
# or: find $inc -wholename *Some/Simple.pm;
done

2012/03/21

Remove dot files

# removes temporary files starting with '.' (excludes '.' '..')
ls -d .* | grep -v '^.svn$' | grep -v '^.$' | grep -v '^..$' | xargs rm
# or
rm -r * && rm .*

2012/03/20

local::lib

Install local::lib:

http://search.cpan.org/search?query=local%3A%3Alib&mode=all
tar xzf local-lib-1.003003.tar.gz
cd local-lib-1.003003/
perl Makefile.PL --bootstrap
make test && make install

or:

sudo apt-get install liblocal-lib-perl

Append to .bashrc:
echo '[ $SHLVL -eq 1 ] && eval "$(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)"' >>~/.bashrc

Re-read configuration file:
. ~/.bashrc

Install cpanm:
cpan App::cpanminus

or:

sudo apt-get install cpanminus
Install module:
cpanm Acme::EyeDrops

Now it should appear in ~/perl5/lib/perl5

=================
$ cpan
<cpan[1]> o conf init urllist
# follow the prompts to pick a cpan mirror near you
<cpan[2]> o conf commit
<cpan> exit

o conf prerequisites_policy follow
o conf build_requires_install_policy yes
o conf make_install_make_command 'sudo make'
o conf commit

2012/02/11

.vimrc

Tagbar:
http://www.vim.org/scripts/script.php?script_id=3465
https://livesoncoffee.wordpress.com/2013/04/12/install-tagbar-vim-plugin/

Winmanager:
http://vim.sourceforge.net/scripts/script.php?script_id=1440

Bufexplorer 7.3.5 (for Winmanager 2.41):
http://vim.sourceforge.net/scripts/script.php?script_id=42

Version 1


:filetype plugin on
set nocompatible
set autoindent
set smartindent
set autoread "auto re-read changed file
set showcmd "show partial commands as you type them
set hidden "new buffers can be opened without old ones being saved
set backspace=
set shiftwidth=4
set tabstop=4
map <c-w><c-f> :FirstExplorerWindow<cr>
map `` :BottomExplorerWindow<cr>
map <silent> `1 :nohl<cr>
nnoremap <silent> <cr> :nohl<cr><cr>
let g:winManagerWindowLayout='BufExplorer,TagsExplorer|FileExplorer'
let g:bufExplorerSortBy='number'
let g:winManagerWidth=23
let g:bufExplorerDefaultHelp=0
let g:tagbar_width=30


" Python
autocmd FileType python set expandtab
autocmd FileType thrift set syn=cpp

" disable automatic comment insertion
autocmd FileType * setlocal formatoptions-=c formatoptions-=r formatoptions-=o

" set list
set listchars=tab:»·,trail:·

" shift tabs using TAB or Shift+TAB
map <tab> v>
map <S-tab> v<

map <F1> :WMToggle<cr>
map <F2> :bprev<cr>
map <F3> :bnext<cr>
map <F4> :e

map <F5> :set nolist<cr>
map <F6> :set list<cr>
map <F7> :set noautoindent<cr>:set nosmartindent<cr>
map <F8> :set autoindent<cr>:set smartindent<cr>

map <F9>  :TagbarToggle<cr>
map <F10> :tabprev<cr>
map <F11> :tabnext<cr>
map <F12> :tabnew 

" C++
vmap <silent> {} :s/^/\/\//gi<cr>:nohl<cr>
vmap <silent> }{ :s/^\/\///gi<cr>:nohl<cr>

" SQL
" vmap <silent> <> :s/^/-- /gi<cr>:nohl<cr>
" vmap <silent> >< :s/^-- \=//gi<cr>:nohl<cr>
vmap <silent> <> :s!^\(\s*\)!\1-- !gi<cr>:nohl<cr>
vmap <silent> >< :s!^\(\s*\)-- \=!\1!gi<cr>:nohl<cr>

" spaces
" vmap <silent> <> :s/^/ /gi<cr>:nohl<cr>
" vmap <silent> >< :s/^ \=//gi<cr>:nohl<cr>

" Perl smart (Eclipse)
" vmap <silent> () :s/^/#/gi<cr>:nohl<cr>
" vmap <silent> )( :s!^\(\s*\)# \=!\1!gi<cr>:nohl<cr>

" Python simple
vmap <silent> () :s/^/#/gi<cr>:nohl<cr>
vmap <silent> )( :s/^#\=//gi<cr>:nohl<cr>

" dont use Q for Ex mode
map Q :q
map :Q :q
map W :w
" map :W :w
map D "_d
map DD "_dd
nmap ss :so ~/.vimrc<cr>

sy on
hi Search ctermbg=240
set hlsearch
hi MatchParen ctermbg=242 ctermfg=228
set t_Co=16
hi OverLength ctermbg=238
hi Visual ctermbg=242
match OverLength /\%79v.\+/
hi nonascii guibg=red ctermbg=red
match nonascii /[^\x00-\x7F]/

" trying to make light colorscheme a darker one
hi Comment    ctermfg=33
hi Statement  ctermfg=214
hi PreProc    ctermfg=133
hi SpecialKey ctermfg=33
hi Search     ctermbg=darkblue ctermfg=yellow

set matchpairs+=<:> "Подсвечивать парные скобки для HTML
set nobackup "Не создавать резервных копий файлов
set noswapfile "Не использовать swap-файл
set ignorecase "Игнорировать регистр символов при поиске

"Меню изменения кодировки чтения из файла
set wildmenu
set wcm=<Tab>
menu Encoding.Read.CP1251   :e ++enc=cp1251<CR>
menu Encoding.Read.CP866    :e ++enc=cp866<CR>
menu Encoding.Read.KOI8-U   :e ++enc=koi8-u<CR>
menu Encoding.Read.UTF-8    :e ++enc=utf-8<CR>
map <F9> :emenu Encoding.Read.<TAB>

"Меню изменения кодировки записи в файл (Ctrl-F9)
set wildmenu
set wcm=<Tab>
menu Encoding.Write.CP1251    :set fenc=cp1251<CR>
menu Encoding.Write.CP866     :set fenc=cp866<CR>
menu Encoding.Write.KOI8-U    :set fenc=koi8-u<CR>
menu Encoding.Write.UTF-8     :set fenc=utf-8<CR>
map <C-F9> :emenu Encoding.Write.<TAB>

Version 2


" a must-have
set nocompatible
set autoindent

" JavaScript
autocmd FileType javascript set shiftwidth=4
autocmd FileType javascript set tabstop=4

" disable automatic comment insertion
autocmd FileType * setlocal formatoptions-=c formatoptions-=r formatoptions-=o

set list
set listchars=tab:»·,trail:·

" shift tabs using TAB or Shift+TAB
map <tab> v>
map <S-tab> v<

"map <F2> <esc>:tabprev<cr>
"map <F3> <esc>:tabnext<cr>
map <F2> <esc>:bprev<cr>
map <F3> <esc>:bnext<cr>
map <F4> <esc>:TlistToggle<cr>
:let Tlist_Ctags_Cmd='/home/mivanchenko/bin/ctags'
nmap `` \bv

map <F5> <esc>:set nolist<cr>
map <F6> <esc>:set list<cr>
" map <F7> <esc>:set background=light<cr>
" map <F8> <esc>:set background=dark<cr>
map <F8> <esc>I&_debug(  );<esc>hhi

map <F9> <esc>:set noautoindent<cr>
map <F10> <esc>:set autoindent<cr>
map <F11> <esc>:tabnew
map <F12> <esc>:set enc=cp1251<cr>:edit<cr>

" comment/uncomment blocks of code (in vmode)

" Perl
" vmap () :s/^/# /gi<Enter>
" vmap )( :s/^# \=//gi<Enter>

" C++
" vmap {} :s/^/\/\/ /gi<Enter>
" vmap }{ :s/^\/\/ //gi<Enter>

" SQL
" vmap <> :s/^/-- /gi<Enter>
" vmap >< :s/^-- \=//gi<Enter>

" spaces
" vmap <> :s/^/ /gi<Enter>
" vmap >< :s/^ \=//gi<Enter>



" Perl smart (Eclipse)
vmap () :s/^/#/gi<Enter>
vmap )( :s!^\(\s*\)# \=!\1!gi<Enter>


vmap {} :s!^\(\s*\)!\1\/\/ !gi<Enter>
vmap }{ :s!^\(\s*\)\/\/ \=!\1!gi<Enter>

vmap <> :s!^\(\s*\)!\1-- !gi<Enter>
vmap >< :s!^\(\s*\)-- \=!\1!gi<Enter>

" dont use Q for Ex mode
map Q :q
map :Q :q
map W :w
map :W :w
map D "_d
map DD "_dd
nmap ss :so ~/.vimrc<cr>

:set enc=utf8
" :set enc=cp1251
" :edit

highlight MatchParen ctermbg=242 ctermfg=228

:set t_Co=16
:highlight OverLength ctermbg=238
:highlight Visual ctermbg=242
:match OverLength /\%79v.\+/
:sy on

:hi Search ctermbg=240
:set hlsearch

" trying to make light colorscheme a darker one
:hi Comment        ctermfg=33
:hi Statement      ctermfg=214
:hi PreProc        ctermfg=133
:hi SpecialKey     ctermfg=33



Version 3, for Mac


:filetype plugin on
set nocompatible
set autoindent
set smartindent
set autoread "auto re-read changed file
set showcmd "show partial commands as you type them
set hidden "new buffers can be opened without old ones being saved
set backspace=
set shiftwidth=4
set tabstop=4
set binary

autocmd FileType python set expandtab autoindent nosmartindent backspace=indent softtabstop=4
autocmd FileType javascript set shiftwidth=4
autocmd FileType javascript set tabstop=4

" disable automatic comment insertion
autocmd FileType * setlocal formatoptions-=c formatoptions-=r formatoptions-=o

" set list
set listchars=tab:»·,trail:·

" shift tabs using TAB or Shift+TAB
map <tab> v>
map <S-tab> v<

map <F1> :TagbarToggle<cr>
map <F2> :tabp<cr>
map <F3> :tabn<cr>
map <F4> :tabnew 

map <F5> :set nolist<cr>
map <F6> :set list<cr>
map <F7> :set noautoindent<cr>:set nosmartindent<cr>
map <F8> :set autoindent<cr>:set smartindent<cr>

map <silent> §1 :nohl<cr>

" Perl smart (Eclipse)
vmap () :s/^/#/gi<Enter>§1
vmap )( :s!^\(\s*\)#\=!\1!gi<Enter>§1

" C++ / JavaScript
vmap {} :s!^!\/\/!gi<Enter>§1
vmap }{ :s!^\(\s*\)\/\/\=!\1!gi<Enter>§1

" SQL
vmap <> :s!^\(\s*\)!\1-- !gi<Enter>§1
vmap >< :s!^\(\s*\)-- \=!\1!gi<Enter>§1

sy on

hi Search ctermbg=253
set hlsearch
hi MatchParen ctermbg=242 ctermfg=228
set t_Co=16
hi OverLength ctermbg=238
hi Visual ctermbg=250
match OverLength /\%79v.\+/

set matchpairs+=<:> "Подсвечивать парные скобки для HTML
set nobackup "Не создавать резервных копий файлов
set noswapfile "Не использовать swap-файл
set ignorecase "Игнорировать регистр символов при поиске

"Меню изменения кодировки чтения из файла
set wildmenu
set wcm=<Tab>
menu Encoding.Read.CP1251   :e ++enc=cp1251<CR>
menu Encoding.Read.CP866    :e ++enc=cp866<CR>
menu Encoding.Read.KOI8-U   :e ++enc=koi8-u<CR>
menu Encoding.Read.UTF-8    :e ++enc=utf-8<CR>
map <F9> :emenu Encoding.Read.<TAB>

"Меню изменения кодировки записи в файл (Ctrl-F9)
set wildmenu
set wcm=<Tab>
menu Encoding.Write.CP1251    :set fenc=cp1251<CR>
menu Encoding.Write.CP866     :set fenc=cp866<CR>
menu Encoding.Write.KOI8-U    :set fenc=koi8-u<CR>
menu Encoding.Write.UTF-8     :set fenc=utf-8<CR>
map <C-F9> :emenu Encoding.Write.<TAB>

:set enc=utf8
:let mapleader='§'