Remove debugging statement.
[hcoop/zz_old/gitweb.git] / gitweb.cgi
index 8d73401..6b5bd8a 100755 (executable)
@@ -23,7 +23,7 @@ BEGIN {
 }
 
 our $cgi = new CGI;
-our $version = "1.5.3.4";
+our $version = "debian.1.5.6.1.19.ge6b2";
 our $my_url = $cgi->url();
 our $my_uri = $cgi->url(-absolute => 1);
 
@@ -35,6 +35,10 @@ our $GIT = "/usr/bin/git";
 #our $projectroot = "/pub/scm";
 our $projectroot = "/pub/git";
 
+# fs traversing limit for getting project list
+# the number is relative to the projectroot
+our $project_maxdepth = 2007;
+
 # target of the home link on top of all pages
 our $home_link = $my_uri || "/";
 
@@ -54,6 +58,8 @@ our $site_header = "";
 our $home_text = "indextext.html";
 # filename of html text to include at bottom of each page
 our $site_footer = "";
+# filename of cached version of front page
+our $cached_front_page = "/var/local/lib/gitweb/indexcache.html";
 
 # URI of stylesheets
 our @stylesheets = ("gitweb.css");
@@ -369,11 +375,16 @@ sub filter_snapshot_fmts {
 
 }
 
-our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "/etc/gitweb.conf";
-do $GITWEB_CONFIG if -e $GITWEB_CONFIG;
+our $GITWEB_CONFIG = $ENV{'GITWEB_CONFIG'} || "gitweb_config.perl";
+if (-e $GITWEB_CONFIG) {
+       do $GITWEB_CONFIG;
+} else {
+       our $GITWEB_CONFIG_SYSTEM = $ENV{'GITWEB_CONFIG_SYSTEM'} || "/etc/gitweb.conf";
+       do $GITWEB_CONFIG_SYSTEM if -e $GITWEB_CONFIG_SYSTEM;
+}
 
 # version of the core git binary
-our $git_version = qx($GIT --version) =~ m/git version (.*)$/ ? $1 : "unknown";
+our $git_version = qx("$GIT" --version) =~ m/git version (.*)$/ ? $1 : "unknown";
 
 $projects_list ||= $projectroot;
 
@@ -413,6 +424,38 @@ if (defined $file_parent) {
        }
 }
 
+sub git_send_cached_front_page {
+       my $status = shift || "200 OK";
+       my $expires = shift;
+       my $content_type;
+       # require explicit support from the UA if we are to send the page as
+       # 'application/xhtml+xml', otherwise send it as plain old 'text/html'.
+       # we have to do this because MSIE sometimes globs '*/*', pretending to
+       # support xhtml+xml but choking when it gets what it asked for.
+       if (defined $cgi->http('HTTP_ACCEPT') &&
+           $cgi->http('HTTP_ACCEPT') =~ m/(,|;|\s|^)application\/xhtml\+xml(,|;|\s|$)/ &&
+           $cgi->Accept('application/xhtml+xml') != 0) {
+               $content_type = 'application/xhtml+xml';
+       } else {
+               $content_type = 'text/html';
+       }
+       print $cgi->header(-type=>$content_type, -charset => 'utf-8',
+                          -status=> $status, -expires => $expires);
+       open (my $fd, $cached_front_page);
+       print <$fd>;
+       close $fd;
+       exit;
+}
+
+# Display a cached page if no parameters were provided and the
+# "nocache" parameter was not passed.
+our $nocache = $cgi->param('nocache');
+our @params = $cgi->Vars;
+if ($cached_front_page && ! defined $nocache && scalar @params == 0
+    && -f $cached_front_page && -r $cached_front_page) {
+       git_send_cached_front_page();
+}
+
 # parameters which are refnames
 our $hash = $cgi->param('h');
 if (defined $hash) {
@@ -473,13 +516,15 @@ if (defined $searchtype) {
        }
 }
 
+our $search_use_regexp = $cgi->param('sr');
+
 our $searchtext = $cgi->param('s');
 our $search_regexp;
 if (defined $searchtext) {
        if (length($searchtext) < 2) {
                die_error(undef, "At least two characters are required for search parameter");
        }
-       $search_regexp = quotemeta $searchtext;
+       $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext;
 }
 
 # now read PATH_INFO and use it as alternative to parameters
@@ -505,7 +550,7 @@ sub evaluate_path_info {
        }
        # do not change any parameters if an action is given using the query string
        return if $action;
-       $path_info =~ s,^$project/*,,;
+       $path_info =~ s,^\Q$project\E/*,,;
        my ($refname, $pathname) = split(/:/, $path_info, 2);
        if (defined $pathname) {
                # we got "project.git/branch:filename" or "project.git/branch:dir/"
@@ -586,7 +631,7 @@ exit;
 ## ======================================================================
 ## action links
 
-sub href(%) {
+sub href (%) {
        my %params = @_;
        # default is to use -absolute url() i.e. $my_uri
        my $href = $params{-full} ? $my_url : $my_uri;
@@ -609,15 +654,25 @@ sub href(%) {
                searchtype => "st",
                snapshot_format => "sf",
                extra_options => "opt",
+               search_use_regexp => "sr",
        );
        my %mapping = @mapping;
 
        $params{'project'} = $project unless exists $params{'project'};
 
+       if ($params{-replay}) {
+               while (my ($name, $symbol) = each %mapping) {
+                       if (!exists $params{$name}) {
+                               # to allow for multivalued params we use arrayref form
+                               $params{$name} = [ $cgi->param($symbol) ];
+                       }
+               }
+       }
+
        my ($use_pathinfo) = gitweb_check_feature('pathinfo');
        if ($use_pathinfo) {
                # use PATH_INFO for project name
-               $href .= "/$params{'project'}" if defined $params{'project'};
+               $href .= "/".esc_url($params{'project'}) if defined $params{'project'};
                delete $params{'project'};
 
                # Summary just uses the project path URL
@@ -687,10 +742,9 @@ sub validate_refname {
 # in utf-8 thanks to "binmode STDOUT, ':utf8'" at beginning
 sub to_utf8 {
        my $str = shift;
-       my $res;
-       eval { $res = decode_utf8($str, Encode::FB_CROAK); };
-       if (defined $res) {
-               return $res;
+       if (utf8::valid($str)) {
+               utf8::decode($str);
+               return $str;
        } else {
                return decode($fallback_encoding, $str, Encode::FB_DEFAULT);
        }
@@ -746,29 +800,40 @@ sub esc_path {
 # Make control characters "printable", using character escape codes (CEC)
 sub quot_cec {
        my $cntrl = shift;
+       my %opts = @_;
        my %es = ( # character escape codes, aka escape sequences
-                  "\t" => '\t',   # tab            (HT)
-                  "\n" => '\n',   # line feed      (LF)
-                  "\r" => '\r',   # carrige return (CR)
-                  "\f" => '\f',   # form feed      (FF)
-                  "\b" => '\b',   # backspace      (BS)
-                  "\a" => '\a',   # alarm (bell)   (BEL)
-                  "\e" => '\e',   # escape         (ESC)
-                  "\013" => '\v', # vertical tab   (VT)
-                  "\000" => '\0', # nul character  (NUL)
-                  );
+               "\t" => '\t',   # tab            (HT)
+               "\n" => '\n',   # line feed      (LF)
+               "\r" => '\r',   # carrige return (CR)
+               "\f" => '\f',   # form feed      (FF)
+               "\b" => '\b',   # backspace      (BS)
+               "\a" => '\a',   # alarm (bell)   (BEL)
+               "\e" => '\e',   # escape         (ESC)
+               "\013" => '\v', # vertical tab   (VT)
+               "\000" => '\0', # nul character  (NUL)
+       );
        my $chr = ( (exists $es{$cntrl})
                    ? $es{$cntrl}
                    : sprintf('\%03o', ord($cntrl)) );
-       return "<span class=\"cntrl\">$chr</span>";
+       if ($opts{-nohtml}) {
+               return $chr;
+       } else {
+               return "<span class=\"cntrl\">$chr</span>";
+       }
 }
 
 # Alternatively use unicode control pictures codepoints,
 # Unicode "printable representation" (PR)
 sub quot_upr {
        my $cntrl = shift;
+       my %opts = @_;
+
        my $chr = sprintf('&#%04d;', 0x2400+ord($cntrl));
-       return "<span class=\"cntrl\">$chr</span>";
+       if ($opts{-nohtml}) {
+               return $chr;
+       } else {
+               return "<span class=\"cntrl\">$chr</span>";
+       }
 }
 
 # git may return quoted and escaped filenames
@@ -793,7 +858,7 @@ sub unquote {
                        return chr(oct($seq));
                } elsif (exists $es{$seq}) {
                        # C escape sequence, aka character escape code
-                       return $es{$seq}
+                       return $es{$seq};
                }
                # quoted ordinary character
                return $seq;
@@ -830,21 +895,83 @@ sub project_in_list {
 ## ----------------------------------------------------------------------
 ## HTML aware string manipulation
 
+# Try to chop given string on a word boundary between position
+# $len and $len+$add_len. If there is no word boundary there,
+# chop at $len+$add_len. Do not chop if chopped part plus ellipsis
+# (marking chopped part) would be longer than given string.
 sub chop_str {
        my $str = shift;
        my $len = shift;
        my $add_len = shift || 10;
+       my $where = shift || 'right'; # 'left' | 'center' | 'right'
+
+       # Make sure perl knows it is utf8 encoded so we don't
+       # cut in the middle of a utf8 multibyte char.
+       $str = to_utf8($str);
 
        # allow only $len chars, but don't cut a word if it would fit in $add_len
        # if it doesn't fit, cut it if it's still longer than the dots we would add
-       $str =~ m/^(.{0,$len}[^ \/\-_:\.@]{0,$add_len})(.*)/;
-       my $body = $1;
-       my $tail = $2;
-       if (length($tail) > 4) {
-               $tail = " ...";
-               $body =~ s/&[^;]*$//; # remove chopped character entities
+       # remove chopped character entities entirely
+
+       # when chopping in the middle, distribute $len into left and right part
+       # return early if chopping wouldn't make string shorter
+       if ($where eq 'center') {
+               return $str if ($len + 5 >= length($str)); # filler is length 5
+               $len = int($len/2);
+       } else {
+               return $str if ($len + 4 >= length($str)); # filler is length 4
+       }
+
+       # regexps: ending and beginning with word part up to $add_len
+       my $endre = qr/.{$len}\w{0,$add_len}/;
+       my $begre = qr/\w{0,$add_len}.{$len}/;
+
+       if ($where eq 'left') {
+               $str =~ m/^(.*?)($begre)$/;
+               my ($lead, $body) = ($1, $2);
+               if (length($lead) > 4) {
+                       $body =~ s/^[^;]*;// if ($lead =~ m/&[^;]*$/);
+                       $lead = " ...";
+               }
+               return "$lead$body";
+
+       } elsif ($where eq 'center') {
+               $str =~ m/^($endre)(.*)$/;
+               my ($left, $str)  = ($1, $2);
+               $str =~ m/^(.*?)($begre)$/;
+               my ($mid, $right) = ($1, $2);
+               if (length($mid) > 5) {
+                       $left  =~ s/&[^;]*$//;
+                       $right =~ s/^[^;]*;// if ($mid =~ m/&[^;]*$/);
+                       $mid = " ... ";
+               }
+               return "$left$mid$right";
+
+       } else {
+               $str =~ m/^($endre)(.*)$/;
+               my $body = $1;
+               my $tail = $2;
+               if (length($tail) > 4) {
+                       $body =~ s/&[^;]*$//;
+                       $tail = "... ";
+               }
+               return "$body$tail";
+       }
+}
+
+# takes the same arguments as chop_str, but also wraps a <span> around the
+# result with a title attribute if it does get chopped. Additionally, the
+# string is HTML-escaped.
+sub chop_and_escape_str {
+       my ($str) = @_;
+
+       my $chopped = chop_str(@_);
+       if ($chopped eq $str) {
+               return esc_html($chopped);
+       } else {
+               $str =~ s/([[:cntrl:]])/?/g;
+               return $cgi->span({-title=>$str}, esc_html($chopped));
        }
-       return "$body$tail";
 }
 
 ## ----------------------------------------------------------------------
@@ -1364,6 +1491,46 @@ sub format_snapshot_links {
        }
 }
 
+## ......................................................................
+## functions returning values to be passed, perhaps after some
+## transformation, to other functions; e.g. returning arguments to href()
+
+# returns hash to be passed to href to generate gitweb URL
+# in -title key it returns description of link
+sub get_feed_info {
+       my $format = shift || 'Atom';
+       my %res = (action => lc($format));
+
+       # feed links are possible only for project views
+       return unless (defined $project);
+       # some views should link to OPML, or to generic project feed,
+       # or don't have specific feed yet (so they should use generic)
+       return if ($action =~ /^(?:tags|heads|forks|tag|search)$/x);
+
+       my $branch;
+       # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
+       # from tag links; this also makes possible to detect branch links
+       if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
+           (defined $hash      && $hash      =~ m!^refs/heads/(.*)$!)) {
+               $branch = $1;
+       }
+       # find log type for feed description (title)
+       my $type = 'log';
+       if (defined $file_name) {
+               $type  = "history of $file_name";
+               $type .= "/" if ($action eq 'tree');
+               $type .= " on '$branch'" if (defined $branch);
+       } else {
+               $type = "log of $branch" if (defined $branch);
+       }
+
+       $res{-title} = $type;
+       $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
+       $res{'file_name'} = $file_name;
+
+       return %res;
+}
+
 ## ----------------------------------------------------------------------
 ## git utility subroutines, invoking git commands
 
@@ -1372,9 +1539,13 @@ sub git_cmd {
        return $GIT, '--git-dir='.$git_dir;
 }
 
-# returns path to the core git executable and the --git-dir parameter as string
-sub git_cmd_str {
-       return join(' ', git_cmd());
+# quote the given arguments for passing them to the shell
+# quote_command("command", "arg 1", "arg with ' and ! characters")
+# => "'command' 'arg 1' 'arg with '\'' and '\!' characters'"
+# Try to avoid using this function wherever possible.
+sub quote_command {
+       return join(' ',
+                   map( { my $a = $_; $a =~ s/(['!])/'\\$1'/g; "'$a'" } @_ ));
 }
 
 # get HEAD ref of given project as hash
@@ -1407,20 +1578,121 @@ sub git_get_type {
        return $type;
 }
 
+# repository configuration
+our $config_file = '';
+our %config;
+
+# store multiple values for single key as anonymous array reference
+# single values stored directly in the hash, not as [ <value> ]
+sub hash_set_multi {
+       my ($hash, $key, $value) = @_;
+
+       if (!exists $hash->{$key}) {
+               $hash->{$key} = $value;
+       } elsif (!ref $hash->{$key}) {
+               $hash->{$key} = [ $hash->{$key}, $value ];
+       } else {
+               push @{$hash->{$key}}, $value;
+       }
+}
+
+# return hash of git project configuration
+# optionally limited to some section, e.g. 'gitweb'
+sub git_parse_project_config {
+       my $section_regexp = shift;
+       my %config;
+
+       local $/ = "\0";
+
+       open my $fh, "-|", git_cmd(), "config", '-z', '-l',
+               or return;
+
+       while (my $keyval = <$fh>) {
+               chomp $keyval;
+               my ($key, $value) = split(/\n/, $keyval, 2);
+
+               hash_set_multi(\%config, $key, $value)
+                       if (!defined $section_regexp || $key =~ /^(?:$section_regexp)\./o);
+       }
+       close $fh;
+
+       return %config;
+}
+
+# convert config value to boolean, 'true' or 'false'
+# no value, number > 0, 'true' and 'yes' values are true
+# rest of values are treated as false (never as error)
+sub config_to_bool {
+       my $val = shift;
+
+       # strip leading and trailing whitespace
+       $val =~ s/^\s+//;
+       $val =~ s/\s+$//;
+
+       return (!defined $val ||               # section.key
+               ($val =~ /^\d+$/ && $val) ||   # section.key = 1
+               ($val =~ /^(?:true|yes)$/i));  # section.key = true
+}
+
+# convert config value to simple decimal number
+# an optional value suffix of 'k', 'm', or 'g' will cause the value
+# to be multiplied by 1024, 1048576, or 1073741824
+sub config_to_int {
+       my $val = shift;
+
+       # strip leading and trailing whitespace
+       $val =~ s/^\s+//;
+       $val =~ s/\s+$//;
+
+       if (my ($num, $unit) = ($val =~ /^([0-9]*)([kmg])$/i)) {
+               $unit = lc($unit);
+               # unknown unit is treated as 1
+               return $num * ($unit eq 'g' ? 1073741824 :
+                              $unit eq 'm' ?    1048576 :
+                              $unit eq 'k' ?       1024 : 1);
+       }
+       return $val;
+}
+
+# convert config value to array reference, if needed
+sub config_to_multi {
+       my $val = shift;
+
+       return ref($val) ? $val : (defined($val) ? [ $val ] : []);
+}
+
 sub git_get_project_config {
        my ($key, $type) = @_;
 
+       # key sanity check
        return unless ($key);
        $key =~ s/^gitweb\.//;
        return if ($key =~ m/\W/);
 
-       my @x = (git_cmd(), 'config');
-       if (defined $type) { push @x, $type; }
-       push @x, "--get";
-       push @x, "gitweb.$key";
-       my $val = qx(@x);
-       chomp $val;
-       return ($val);
+       # type sanity check
+       if (defined $type) {
+               $type =~ s/^--//;
+               $type = undef
+                       unless ($type eq 'bool' || $type eq 'int');
+       }
+
+       # get config
+       if (!defined $config_file ||
+           $config_file ne "$git_dir/config") {
+               %config = git_parse_project_config('gitweb');
+               $config_file = "$git_dir/config";
+       }
+
+       # ensure given type
+       if (!defined $type) {
+               return $config{"gitweb.$key"};
+       } elsif ($type eq 'bool') {
+               # backward compatibility: 'git config --bool' returns true/false
+               return config_to_bool($config{"gitweb.$key"}) ? 'true' : 'false';
+       } elsif ($type eq 'int') {
+               return config_to_int($config{"gitweb.$key"});
+       }
+       return $config{"gitweb.$key"};
 }
 
 # get hash of given path at given ref
@@ -1480,7 +1752,9 @@ sub git_get_path_by_hash {
 sub git_get_project_description {
        my $path = shift;
 
-       open my $fd, "$projectroot/$path/description" or return undef;
+       $git_dir = "$projectroot/$path";
+       open my $fd, "$git_dir/description"
+               or return git_get_project_config('description');
        my $descr = <$fd>;
        close $fd;
        if (defined $descr) {
@@ -1492,7 +1766,11 @@ sub git_get_project_description {
 sub git_get_project_url_list {
        my $path = shift;
 
-       open my $fd, "$projectroot/$path/cloneurl" or return;
+       $git_dir = "$projectroot/$path";
+       open my $fd, "$git_dir/cloneurl"
+               or return wantarray ?
+               @{ config_to_multi(git_get_project_config('url')) } :
+                  config_to_multi(git_get_project_config('url'));
        my @git_project_url_list = map { chomp; $_ } <$fd>;
        close $fd;
 
@@ -1514,6 +1792,7 @@ sub git_get_projects_list {
                # remove the trailing "/"
                $dir =~ s!/+$!!;
                my $pfxlen = length("$dir");
+               my $pfxdepth = ($dir =~ tr!/!!);
 
                File::Find::find({
                        follow_fast => 1, # follow symbolic links
@@ -1524,6 +1803,11 @@ sub git_get_projects_list {
                                return if (m!^[/.]$!);
                                # only directories can be git repositories
                                return unless (-d $_);
+                               # don't traverse too deep (Find is super slow on os x)
+                               if (($File::Find::name =~ tr!/!!) - $pfxdepth > $project_maxdepth) {
+                                       $File::Find::prune = 1;
+                                       return;
+                               }
 
                                my $subdir = substr($File::Find::name, $pfxlen + 1);
                                # we check related file in $projectroot
@@ -1622,6 +1906,7 @@ sub git_get_project_owner {
        my $owner;
 
        return undef unless $project;
+       $git_dir = "$projectroot/$project";
 
        if (!defined $gitweb_project_owner) {
                git_get_project_list_from_file();
@@ -1630,8 +1915,11 @@ sub git_get_project_owner {
        if (exists $gitweb_project_owner->{$project}) {
                $owner = $gitweb_project_owner->{$project};
        }
+       if (!defined $owner){
+               $owner = git_get_project_config('owner');
+       }
        if (!defined $owner) {
-               $owner = get_file_owner("$projectroot/$project");
+               $owner = get_file_owner("$git_dir");
        }
 
        return $owner;
@@ -1718,7 +2006,7 @@ sub parse_date {
        $date{'mday-time'} = sprintf "%d %s %02d:%02d",
                             $mday, $months[$mon], $hour ,$min;
        $date{'iso-8601'}  = sprintf "%04d-%02d-%02dT%02d:%02d:%02dZ",
-                            1900+$year, $mon, $mday, $hour ,$min, $sec;
+                            1900+$year, 1+$mon, $mday, $hour ,$min, $sec;
 
        $tz =~ m/^([+\-][0-9][0-9])([0-9][0-9])$/;
        my $local = $epoch + ((int $1 + ($2/60)) * 3600);
@@ -1886,7 +2174,7 @@ sub parse_commit {
 }
 
 sub parse_commits {
-       my ($commit_id, $maxcount, $skip, $arg, $filename) = @_;
+       my ($commit_id, $maxcount, $skip, $filename, @args) = @_;
        my @cos;
 
        $maxcount ||= 1;
@@ -1896,7 +2184,7 @@ sub parse_commits {
 
        open my $fd, "-|", git_cmd(), "rev-list",
                "--header",
-               ($arg ? ($arg) : ()),
+               @args,
                ("--max-count=" . $maxcount),
                ("--skip=" . $skip),
                @extra_options,
@@ -1913,49 +2201,6 @@ sub parse_commits {
        return wantarray ? @cos : \@cos;
 }
 
-# parse ref from ref_file, given by ref_id, with given type
-sub parse_ref {
-       my $ref_file = shift;
-       my $ref_id = shift;
-       my $type = shift || git_get_type($ref_id);
-       my %ref_item;
-
-       $ref_item{'type'} = $type;
-       $ref_item{'id'} = $ref_id;
-       $ref_item{'epoch'} = 0;
-       $ref_item{'age'} = "unknown";
-       if ($type eq "tag") {
-               my %tag = parse_tag($ref_id);
-               $ref_item{'comment'} = $tag{'comment'};
-               if ($tag{'type'} eq "commit") {
-                       my %co = parse_commit($tag{'object'});
-                       $ref_item{'epoch'} = $co{'committer_epoch'};
-                       $ref_item{'age'} = $co{'age_string'};
-               } elsif (defined($tag{'epoch'})) {
-                       my $age = time - $tag{'epoch'};
-                       $ref_item{'epoch'} = $tag{'epoch'};
-                       $ref_item{'age'} = age_string($age);
-               }
-               $ref_item{'reftype'} = $tag{'type'};
-               $ref_item{'name'} = $tag{'name'};
-               $ref_item{'refid'} = $tag{'object'};
-       } elsif ($type eq "commit"){
-               my %co = parse_commit($ref_id);
-               $ref_item{'reftype'} = "commit";
-               $ref_item{'name'} = $ref_file;
-               $ref_item{'title'} = $co{'title'};
-               $ref_item{'refid'} = $ref_id;
-               $ref_item{'epoch'} = $co{'committer_epoch'};
-               $ref_item{'age'} = $co{'age_string'};
-       } else {
-               $ref_item{'reftype'} = $type;
-               $ref_item{'name'} = $ref_file;
-               $ref_item{'refid'} = $ref_id;
-       }
-
-       return %ref_item;
-}
-
 # parse line of git-diff-tree "raw" output
 sub parse_difftree_raw_line {
        my $line = shift;
@@ -1973,7 +2218,7 @@ sub parse_difftree_raw_line {
                if ($res{'status'} eq 'R' || $res{'status'} eq 'C') { # renamed or copied
                        ($res{'from_file'}, $res{'to_file'}) = map { unquote($_) } split("\t", $7);
                } else {
-                       $res{'file'} = unquote($7);
+                       $res{'from_file'} = $res{'to_file'} = $res{'file'} = unquote($7);
                }
        }
        # '::100755 100755 100755 60e79ca1b01bc8b057abe17ddab484699a7f5fdb 94067cc5f73388f33722d52ae02f44692bc07490 94067cc5f73388f33722d52ae02f44692bc07490 MR git-gui/git-gui.sh'
@@ -1995,6 +2240,19 @@ sub parse_difftree_raw_line {
        return wantarray ? %res : \%res;
 }
 
+# wrapper: return parsed line of git-diff-tree "raw" output
+# (the argument might be raw line, or parsed info)
+sub parsed_difftree_line {
+       my $line_or_ref = shift;
+
+       if (ref($line_or_ref) eq "HASH") {
+               # pre-parsed (or generated by hand)
+               return $line_or_ref;
+       } else {
+               return parse_difftree_raw_line($line_or_ref);
+       }
+}
+
 # parse line of git-ls-tree output
 sub parse_ls_tree_line ($;%) {
        my $line = shift;
@@ -2027,7 +2285,10 @@ sub parse_from_to_diffinfo {
                fill_from_file_info($diffinfo, @parents)
                        unless exists $diffinfo->{'from_file'};
                for (my $i = 0; $i < $diffinfo->{'nparents'}; $i++) {
-                       $from->{'file'}[$i] = $diffinfo->{'from_file'}[$i] || $diffinfo->{'to_file'};
+                       $from->{'file'}[$i] =
+                               defined $diffinfo->{'from_file'}[$i] ?
+                                       $diffinfo->{'from_file'}[$i] :
+                                       $diffinfo->{'to_file'};
                        if ($diffinfo->{'status'}[$i] ne "A") { # not new (added) file
                                $from->{'href'}[$i] = href(action=>"blob",
                                                           hash_base=>$parents[$i],
@@ -2038,7 +2299,8 @@ sub parse_from_to_diffinfo {
                        }
                }
        } else {
-               $from->{'file'} = $diffinfo->{'from_file'} || $diffinfo->{'file'};
+               # ordinary (not combined) diff
+               $from->{'file'} = $diffinfo->{'from_file'};
                if ($diffinfo->{'status'} ne "A") { # not new (added) file
                        $from->{'href'} = href(action=>"blob", hash_base=>$hash_parent,
                                               hash=>$diffinfo->{'from_id'},
@@ -2048,7 +2310,7 @@ sub parse_from_to_diffinfo {
                }
        }
 
-       $to->{'file'} = $diffinfo->{'to_file'} || $diffinfo->{'file'};
+       $to->{'file'} = $diffinfo->{'to_file'};
        if (!is_deleted($diffinfo)) { # file exists in result
                $to->{'href'} = href(action=>"blob", hash_base=>$hash,
                                     hash=>$diffinfo->{'to_id'},
@@ -2078,6 +2340,7 @@ sub git_get_heads_list {
                my ($hash, $name, $title) = split(' ', $refinfo, 3);
                my ($committer, $epoch, $tz) =
                        ($committerinfo =~ /^(.*) ([0-9]+) (.*)$/);
+               $ref_item{'fullname'}  = $name;
                $name =~ s!^refs/heads/!!;
 
                $ref_item{'name'}  = $name;
@@ -2115,6 +2378,7 @@ sub git_get_tags_list {
                my ($id, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
                my ($creator, $epoch, $tz) =
                        ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
+               $ref_item{'fullname'} = $name;
                $name =~ s!^refs/tags/!!;
 
                $ref_item{'type'} = $type;
@@ -2217,8 +2481,7 @@ sub blob_mimetype {
        return $default_blob_plain_mimetype unless $fd;
 
        if (-T $fd) {
-               return 'text/plain' .
-                      ($default_text_plain_charset ? '; charset='.$default_text_plain_charset : '');
+               return 'text/plain';
        } elsif (! $filename) {
                return 'application/octet-stream';
        } elsif ($filename =~ m/\.png$/i) {
@@ -2232,6 +2495,17 @@ sub blob_mimetype {
        }
 }
 
+sub blob_contenttype {
+       my ($fd, $file_name, $type) = @_;
+
+       $type ||= blob_mimetype($fd, $file_name);
+       if ($type eq 'text/plain' && defined $default_text_plain_charset) {
+               $type .= "; charset=$default_text_plain_charset";
+       }
+
+       return $type;
+}
+
 ## ======================================================================
 ## functions printing HTML: header, footer, error page
 
@@ -2290,30 +2564,49 @@ EOF
                }
        }
        if (defined $project) {
-               printf('<link rel="alternate" title="%s log RSS feed" '.
-                      'href="%s" type="application/rss+xml" />'."\n",
-                      esc_param($project), href(action=>"rss"));
-               printf('<link rel="alternate" title="%s log RSS feed (no merges)" '.
-                      'href="%s" type="application/rss+xml" />'."\n",
-                      esc_param($project), href(action=>"rss",
-                                                extra_options=>"--no-merges"));
-               printf('<link rel="alternate" title="%s log Atom feed" '.
-                      'href="%s" type="application/atom+xml" />'."\n",
-                      esc_param($project), href(action=>"atom"));
-               printf('<link rel="alternate" title="%s log Atom feed (no merges)" '.
-                      'href="%s" type="application/atom+xml" />'."\n",
-                      esc_param($project), href(action=>"atom",
-                                                extra_options=>"--no-merges"));
+               my %href_params = get_feed_info();
+               if (!exists $href_params{'-title'}) {
+                       $href_params{'-title'} = 'log';
+               }
+
+               foreach my $format qw(RSS Atom) {
+                       my $type = lc($format);
+                       my %link_attr = (
+                               '-rel' => 'alternate',
+                               '-title' => "$project - $href_params{'-title'} - $format feed",
+                               '-type' => "application/$type+xml"
+                       );
+
+                       $href_params{'action'} = $type;
+                       $link_attr{'-href'} = href(%href_params);
+                       print "<link ".
+                             "rel=\"$link_attr{'-rel'}\" ".
+                             "title=\"$link_attr{'-title'}\" ".
+                             "href=\"$link_attr{'-href'}\" ".
+                             "type=\"$link_attr{'-type'}\" ".
+                             "/>\n";
+
+                       $href_params{'extra_options'} = '--no-merges';
+                       $link_attr{'-href'} = href(%href_params);
+                       $link_attr{'-title'} .= ' (no merges)';
+                       print "<link ".
+                             "rel=\"$link_attr{'-rel'}\" ".
+                             "title=\"$link_attr{'-title'}\" ".
+                             "href=\"$link_attr{'-href'}\" ".
+                             "type=\"$link_attr{'-type'}\" ".
+                             "/>\n";
+               }
+
        } else {
                printf('<link rel="alternate" title="%s projects list" '.
-                      'href="%s" type="text/plain; charset=utf-8"/>'."\n",
+                      'href="%s" type="text/plain; charset=utf-8" />'."\n",
                       $site_name, href(project=>undef, action=>"project_index"));
                printf('<link rel="alternate" title="%s projects feeds" '.
-                      'href="%s" type="text/x-opml"/>'."\n",
+                      'href="%s" type="text/x-opml" />'."\n",
                       $site_name, href(project=>undef, action=>"opml"));
        }
        if (defined $favicon) {
-               print qq(<link rel="shortcut icon" href="$favicon" type="image/png"/>\n);
+               print qq(<link rel="shortcut icon" href="$favicon" type="image/png" />\n);
        }
 
        print "</head>\n" .
@@ -2340,7 +2633,7 @@ EOF
        print "</div>\n";
 
        my ($have_search) = gitweb_check_feature('search');
-       if ((defined $project) && ($have_search)) {
+       if (defined $project && $have_search) {
                if (!defined $searchtext) {
                        $searchtext = "";
                }
@@ -2355,45 +2648,58 @@ EOF
                my $action = $my_uri;
                my ($use_pathinfo) = gitweb_check_feature('pathinfo');
                if ($use_pathinfo) {
-                       $action .= "/$project";
-               } else {
-                       $cgi->param("p", $project);
+                       $action .= "/".esc_url($project);
                }
-               $cgi->param("a", "search");
-               $cgi->param("h", $search_hash);
                print $cgi->startform(-method => "get", -action => $action) .
                      "<div class=\"search\">\n" .
-                     (!$use_pathinfo && $cgi->hidden(-name => "p") . "\n") .
-                     $cgi->hidden(-name => "a") . "\n" .
-                     $cgi->hidden(-name => "h") . "\n" .
+                     (!$use_pathinfo &&
+                     $cgi->input({-name=>"p", -value=>$project, -type=>"hidden"}) . "\n") .
+                     $cgi->input({-name=>"a", -value=>"search", -type=>"hidden"}) . "\n" .
+                     $cgi->input({-name=>"h", -value=>$search_hash, -type=>"hidden"}) . "\n" .
                      $cgi->popup_menu(-name => 'st', -default => 'commit',
                                       -values => ['commit', 'grep', 'author', 'committer', 'pickaxe']) .
                      $cgi->sup($cgi->a({-href => href(action=>"search_help")}, "?")) .
                      " search:\n",
                      $cgi->textfield(-name => "s", -value => $searchtext) . "\n" .
+                     "<span title=\"Extended regular expression\">" .
+                     $cgi->checkbox(-name => 'sr', -value => 1, -label => 're',
+                                    -checked => $search_use_regexp) .
+                     "</span>" .
                      "</div>" .
                      $cgi->end_form() . "\n";
        }
 }
 
 sub git_footer_html {
+       my $feed_class = 'rss_logo';
+
        print "<div class=\"page_footer\">\n";
        if (defined $project) {
                my $descr = git_get_project_description($project);
                if (defined $descr) {
                        print "<div class=\"page_footer_text\">" . esc_html($descr) . "</div>\n";
                }
-               print $cgi->a({-href => href(action=>"rss"),
-                             -class => "rss_logo"}, "RSS") . " ";
-               print $cgi->a({-href => href(action=>"atom"),
-                             -class => "rss_logo"}, "Atom") . "\n";
+
+               my %href_params = get_feed_info();
+               if (!%href_params) {
+                       $feed_class .= ' generic';
+               }
+               $href_params{'-title'} ||= 'log';
+
+               foreach my $format qw(RSS Atom) {
+                       $href_params{'action'} = lc($format);
+                       print $cgi->a({-href => href(%href_params),
+                                     -title => "$href_params{'-title'} $format feed",
+                                     -class => $feed_class}, $format)."\n";
+               }
+
        } else {
                print $cgi->a({-href => href(project=>undef, action=>"opml"),
-                             -class => "rss_logo"}, "OPML") . " ";
+                             -class => $feed_class}, "OPML") . " ";
                print $cgi->a({-href => href(project=>undef, action=>"project_index"),
-                             -class => "rss_logo"}, "TXT") . "\n";
+                             -class => $feed_class}, "TXT") . "\n";
        }
-       print "</div>\n" ;
+       print "</div>\n"; # class="page_footer"
 
        if (-f $site_footer) {
                open (my $fd, $site_footer);
@@ -2457,7 +2763,7 @@ sub git_print_page_nav {
 }
 
 sub format_paging_nav {
-       my ($action, $hash, $head, $page, $nrevs) = @_;
+       my ($action, $hash, $head, $page, $has_next_link) = @_;
        my $paging_nav;
 
 
@@ -2469,15 +2775,15 @@ sub format_paging_nav {
 
        if ($page > 0) {
                $paging_nav .= " &sdot; " .
-                       $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page-1),
+                       $cgi->a({-href => href(-replay=>1, page=>$page-1),
                                 -accesskey => "p", -title => "Alt-p"}, "prev");
        } else {
                $paging_nav .= " &sdot; prev";
        }
 
-       if ($nrevs >= (100 * ($page+1)-1)) {
+       if ($has_next_link) {
                $paging_nav .= " &sdot; " .
-                       $cgi->a({-href => href(action=>$action, hash=>$hash, page=>$page+1),
+                       $cgi->a({-href => href(-replay=>1, page=>$page+1),
                                 -accesskey => "n", -title => "Alt-n"}, "next");
        } else {
                $paging_nav .= " &sdot; next";
@@ -2761,6 +3067,7 @@ sub git_print_tree_entry {
 ## ......................................................................
 ## functions printing large fragments of HTML
 
+# get pre-image filenames for merge (combined) diff
 sub fill_from_file_info {
        my ($diff, @parents) = @_;
 
@@ -2777,28 +3084,25 @@ sub fill_from_file_info {
        return $diff;
 }
 
-# parameters can be strings, or references to arrays of strings
-sub from_ids_eq {
-       my ($a, $b) = @_;
-
-       if (ref($a) eq "ARRAY" && ref($b) eq "ARRAY" && @$a == @$b) {
-               for (my $i = 0; $i < @$a; ++$i) {
-                       return 0 unless ($a->[$i] eq $b->[$i]);
-               }
-               return 1;
-       } elsif (!ref($a) && !ref($b)) {
-               return $a eq $b;
-       } else {
-               return 0;
-       }
-}
-
+# is current raw difftree line of file deletion
 sub is_deleted {
        my $diffinfo = shift;
 
        return $diffinfo->{'to_id'} eq ('0' x 40);
 }
 
+# does patch correspond to [previous] difftree raw line
+# $diffinfo  - hashref of parsed raw diff format
+# $patchinfo - hashref of parsed patch diff format
+#              (the same keys as in $diffinfo)
+sub is_patch_split {
+       my ($diffinfo, $patchinfo) = @_;
+
+       return defined $diffinfo && defined $patchinfo
+               && $diffinfo->{'to_file'} eq $patchinfo->{'to_file'};
+}
+
+
 sub git_difftree_body {
        my ($difftree, $hash, @parents) = @_;
        my ($parent) = $parents[0];
@@ -2835,13 +3139,7 @@ sub git_difftree_body {
        my $alternate = 1;
        my $patchno = 0;
        foreach my $line (@{$difftree}) {
-               my $diff;
-               if (ref($line) eq "HASH") {
-                       # pre-parsed (or generated by hand)
-                       $diff = $line;
-               } else {
-                       $diff = parse_difftree_raw_line($line);
-               }
+               my $diff = parsed_difftree_line($line);
 
                if ($alternate) {
                        print "<tr class=\"dark\">\n";
@@ -3112,10 +3410,12 @@ sub git_patchset_body {
        my ($fd, $difftree, $hash, @hash_parents) = @_;
        my ($hash_parent) = $hash_parents[0];
 
+       my $is_combined = (@hash_parents > 1);
        my $patch_idx = 0;
        my $patch_number = 0;
        my $patch_line;
        my $diffinfo;
+       my $to_name;
        my (%from, %to);
 
        print "<div class=\"patchset\">\n";
@@ -3129,73 +3429,46 @@ sub git_patchset_body {
 
  PATCH:
        while ($patch_line) {
-               my @diff_header;
-               my ($from_id, $to_id);
-
-               # git diff header
-               #assert($patch_line =~ m/^diff /) if DEBUG;
-               #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
-               $patch_number++;
-               push @diff_header, $patch_line;
 
-               # extended diff header
-       EXTENDED_HEADER:
-               while ($patch_line = <$fd>) {
-                       chomp $patch_line;
-
-                       last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
-
-                       if ($patch_line =~ m/^index ([0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
-                               $from_id = $1;
-                               $to_id   = $2;
-                       } elsif ($patch_line =~ m/^index ((?:[0-9a-fA-F]{40},)+[0-9a-fA-F]{40})..([0-9a-fA-F]{40})/) {
-                               $from_id = [ split(',', $1) ];
-                               $to_id   = $2;
-                       }
-
-                       push @diff_header, $patch_line;
+               # parse "git diff" header line
+               if ($patch_line =~ m/^diff --git (\"(?:[^\\\"]*(?:\\.[^\\\"]*)*)\"|[^ "]*) (.*)$/) {
+                       # $1 is from_name, which we do not use
+                       $to_name = unquote($2);
+                       $to_name =~ s!^b/!!;
+               } elsif ($patch_line =~ m/^diff --(cc|combined) ("?.*"?)$/) {
+                       # $1 is 'cc' or 'combined', which we do not use
+                       $to_name = unquote($2);
+               } else {
+                       $to_name = undef;
                }
-               my $last_patch_line = $patch_line;
 
                # check if current patch belong to current raw line
                # and parse raw git-diff line if needed
-               if (defined $diffinfo &&
-                   defined $from_id && defined $to_id &&
-                   from_ids_eq($diffinfo->{'from_id'}, $from_id) &&
-                   $diffinfo->{'to_id'} eq $to_id) {
+               if (is_patch_split($diffinfo, { 'to_file' => $to_name })) {
                        # this is continuation of a split patch
                        print "<div class=\"patch cont\">\n";
                } else {
                        # advance raw git-diff output if needed
                        $patch_idx++ if defined $diffinfo;
 
-                       # compact combined diff output can have some patches skipped
-                       # find which patch (using pathname of result) we are at now
-                       my $to_name;
-                       if ($diff_header[0] =~ m!^diff --cc "?(.*)"?$!) {
-                               $to_name = $1;
-                       }
-
-                       do {
-                               # read and prepare patch information
-                               if (ref($difftree->[$patch_idx]) eq "HASH") {
-                                       # pre-parsed (or generated by hand)
-                                       $diffinfo = $difftree->[$patch_idx];
-                               } else {
-                                       $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
-                               }
+                       # read and prepare patch information
+                       $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
 
-                               # check if current raw line has no patch (it got simplified)
-                               if (defined $to_name && $to_name ne $diffinfo->{'to_file'}) {
+                       # compact combined diff output can have some patches skipped
+                       # find which patch (using pathname of result) we are at now;
+                       if ($is_combined) {
+                               while ($to_name ne $diffinfo->{'to_file'}) {
                                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
                                              format_diff_cc_simplified($diffinfo, @hash_parents) .
                                              "</div>\n";  # class="patch"
 
                                        $patch_idx++;
                                        $patch_number++;
+
+                                       last if $patch_idx > $#$difftree;
+                                       $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
                                }
-                       } until (!defined $to_name || $to_name eq $diffinfo->{'to_file'} ||
-                                $patch_idx > $#$difftree);
+                       }
 
                        # modifies %from, %to hashes
                        parse_from_to_diffinfo($diffinfo, \%from, \%to, @hash_parents);
@@ -3205,30 +3478,36 @@ sub git_patchset_body {
                        print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n";
                }
 
+               # git diff header
+               #assert($patch_line =~ m/^diff /) if DEBUG;
+               #assert($patch_line !~ m!$/$!) if DEBUG; # is chomp-ed
+               $patch_number++;
                # print "git diff" header
-               $patch_line = shift @diff_header;
                print format_git_diff_header_line($patch_line, $diffinfo,
                                                  \%from, \%to);
 
                # print extended diff header
-               print "<div class=\"diff extended_header\">\n" if (@diff_header > 0);
+               print "<div class=\"diff extended_header\">\n";
        EXTENDED_HEADER:
-               foreach $patch_line (@diff_header) {
+               while ($patch_line = <$fd>) {
+                       chomp $patch_line;
+
+                       last EXTENDED_HEADER if ($patch_line =~ m/^--- |^diff /);
+
                        print format_extended_diff_header_line($patch_line, $diffinfo,
                                                               \%from, \%to);
                }
-               print "</div>\n"  if (@diff_header > 0); # class="diff extended_header"
+               print "</div>\n"; # class="diff extended_header"
 
                # from-file/to-file diff header
-               $patch_line = $last_patch_line;
                if (! $patch_line) {
                        print "</div>\n"; # class="patch"
                        last PATCH;
                }
                next PATCH if ($patch_line =~ m/^diff /);
                #assert($patch_line =~ m/^---/) if DEBUG;
-               #assert($patch_line eq $last_patch_line) if DEBUG;
 
+               my $last_patch_line = $patch_line;
                $patch_line = <$fd>;
                chomp $patch_line;
                #assert($patch_line =~ m/^\+\+\+/) if DEBUG;
@@ -3253,16 +3532,11 @@ sub git_patchset_body {
 
        # for compact combined (--cc) format, with chunk and patch simpliciaction
        # patchset might be empty, but there might be unprocessed raw lines
-       for ($patch_idx++ if $patch_number > 0;
+       for (++$patch_idx if $patch_number > 0;
             $patch_idx < @$difftree;
-            $patch_idx++) {
+            ++$patch_idx) {
                # read and prepare patch information
-               if (ref($difftree->[$patch_idx]) eq "HASH") {
-                       # pre-parsed (or generated by hand)
-                       $diffinfo = $difftree->[$patch_idx];
-               } else {
-                       $diffinfo = parse_difftree_raw_line($difftree->[$patch_idx]);
-               }
+               $diffinfo = parsed_difftree_line($difftree->[$patch_idx]);
 
                # generate anchor for "patch" links in difftree / whatchanged part
                print "<div class=\"patch\" id=\"patch". ($patch_idx+1) ."\">\n" .
@@ -3390,7 +3664,7 @@ sub git_project_list_body {
                      "<td>" . $cgi->a({-href => href(project=>$pr->{'path'}, action=>"summary"),
                                        -class => "list", -title => $pr->{'descr_long'}},
                                        esc_html($pr->{'descr'})) . "</td>\n" .
-                     "<td><i>" . esc_html(chop_str($pr->{'owner'}, 15)) . "</i></td>\n";
+                     "<td><i>" . chop_and_escape_str($pr->{'owner'}, 15) . "</i></td>\n";
                print "<td class=\"". age_class($pr->{'age'}) . "\">" .
                      (defined $pr->{'age_string'} ? $pr->{'age_string'} : "No commits") . "</td>\n" .
                      "<td class=\"link\">" .
@@ -3420,7 +3694,7 @@ sub git_shortlog_body {
        $from = 0 unless defined $from;
        $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
 
-       print "<table class=\"shortlog\" cellspacing=\"0\">\n";
+       print "<table class=\"shortlog\">\n";
        my $alternate = 1;
        for (my $i = $from; $i <= $to; $i++) {
                my %co = %{$commitlist->[$i]};
@@ -3432,9 +3706,10 @@ sub git_shortlog_body {
                        print "<tr class=\"light\">\n";
                }
                $alternate ^= 1;
+               my $author = chop_and_escape_str($co{'author_name'}, 10);
                # git_summary() used print "<td><i>$co{'age_string'}</i></td>\n" .
                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
-                     "<td><i>" . esc_html(chop_str($co{'author_name'}, 10)) . "</i></td>\n" .
+                     "<td><i>" . $author . "</i></td>\n" .
                      "<td>";
                print format_subject_html($co{'title'}, $co{'title_short'},
                                          href(action=>"commit", hash=>$commit), $ref);
@@ -3465,7 +3740,7 @@ sub git_history_body {
        $from = 0 unless defined $from;
        $to = $#{$commitlist} unless (defined $to && $to <= $#{$commitlist});
 
-       print "<table class=\"history\" cellspacing=\"0\">\n";
+       print "<table class=\"history\">\n";
        my $alternate = 1;
        for (my $i = $from; $i <= $to; $i++) {
                my %co = %{$commitlist->[$i]};
@@ -3482,9 +3757,10 @@ sub git_history_body {
                        print "<tr class=\"light\">\n";
                }
                $alternate ^= 1;
+       # shortlog uses      chop_str($co{'author_name'}, 10)
+               my $author = chop_and_escape_str($co{'author_name'}, 15, 3);
                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
-                     # shortlog uses      chop_str($co{'author_name'}, 10)
-                     "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 3)) . "</i></td>\n" .
+                     "<td><i>" . $author . "</i></td>\n" .
                      "<td>";
                # originally git_history used chop_str($co{'title'}, 50)
                print format_subject_html($co{'title'}, $co{'title_short'},
@@ -3524,7 +3800,7 @@ sub git_tags_body {
        $from = 0 unless defined $from;
        $to = $#{$taglist} if (!defined $to || $#{$taglist} < $to);
 
-       print "<table class=\"tags\" cellspacing=\"0\">\n";
+       print "<table class=\"tags\">\n";
        my $alternate = 1;
        for (my $i = $from; $i <= $to; $i++) {
                my $entry = $taglist->[$i];
@@ -3565,8 +3841,8 @@ sub git_tags_body {
                      "<td class=\"link\">" . " | " .
                      $cgi->a({-href => href(action=>$tag{'reftype'}, hash=>$tag{'refid'})}, $tag{'reftype'});
                if ($tag{'reftype'} eq "commit") {
-                       print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'name'})}, "shortlog") .
-                             " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'name'})}, "log");
+                       print " | " . $cgi->a({-href => href(action=>"shortlog", hash=>$tag{'fullname'})}, "shortlog") .
+                             " | " . $cgi->a({-href => href(action=>"log", hash=>$tag{'fullname'})}, "log");
                } elsif ($tag{'reftype'} eq "blob") {
                        print " | " . $cgi->a({-href => href(action=>"blob_plain", hash=>$tag{'refid'})}, "raw");
                }
@@ -3587,7 +3863,7 @@ sub git_heads_body {
        $from = 0 unless defined $from;
        $to = $#{$headlist} if (!defined $to || $#{$headlist} < $to);
 
-       print "<table class=\"heads\" cellspacing=\"0\">\n";
+       print "<table class=\"heads\">\n";
        my $alternate = 1;
        for (my $i = $from; $i <= $to; $i++) {
                my $entry = $headlist->[$i];
@@ -3601,13 +3877,13 @@ sub git_heads_body {
                $alternate ^= 1;
                print "<td><i>$ref{'age'}</i></td>\n" .
                      ($curr ? "<td class=\"current_head\">" : "<td>") .
-                     $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'}),
+                     $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'}),
                               -class => "list name"},esc_html($ref{'name'})) .
                      "</td>\n" .
                      "<td class=\"link\">" .
-                     $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'name'})}, "shortlog") . " | " .
-                     $cgi->a({-href => href(action=>"log", hash=>$ref{'name'})}, "log") . " | " .
-                     $cgi->a({-href => href(action=>"tree", hash=>$ref{'name'}, hash_base=>$ref{'name'})}, "tree") .
+                     $cgi->a({-href => href(action=>"shortlog", hash=>$ref{'fullname'})}, "shortlog") . " | " .
+                     $cgi->a({-href => href(action=>"log", hash=>$ref{'fullname'})}, "log") . " | " .
+                     $cgi->a({-href => href(action=>"tree", hash=>$ref{'fullname'}, hash_base=>$ref{'name'})}, "tree") .
                      "</td>\n" .
                      "</tr>";
        }
@@ -3624,7 +3900,7 @@ sub git_search_grep_body {
        $from = 0 unless defined $from;
        $to = $#{$commitlist} if (!defined $to || $#{$commitlist} < $to);
 
-       print "<table class=\"grep\" cellspacing=\"0\">\n";
+       print "<table class=\"commit_search\">\n";
        my $alternate = 1;
        for (my $i = $from; $i <= $to; $i++) {
                my %co = %{$commitlist->[$i]};
@@ -3638,27 +3914,36 @@ sub git_search_grep_body {
                        print "<tr class=\"light\">\n";
                }
                $alternate ^= 1;
+               my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
                print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
-                     "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
+                     "<td><i>" . $author . "</i></td>\n" .
                      "<td>" .
-                     $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}), -class => "list subject"},
-                              esc_html(chop_str($co{'title'}, 50)) . "<br/>");
+                     $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
+                              -class => "list subject"},
+                             chop_and_escape_str($co{'title'}, 50) . "<br/>");
                my $comment = $co{'comment'};
                foreach my $line (@$comment) {
-                       if ($line =~ m/^(.*)($search_regexp)(.*)$/i) {
-                               my $lead = esc_html($1) || "";
-                               $lead = chop_str($lead, 30, 10);
-                               my $match = esc_html($2) || "";
-                               my $trail = esc_html($3) || "";
-                               $trail = chop_str($trail, 30, 10);
-                               my $text = "$lead<span class=\"match\">$match</span>$trail";
-                               print chop_str($text, 80, 5) . "<br/>\n";
+                       if ($line =~ m/^(.*?)($search_regexp)(.*)$/i) {
+                               my ($lead, $match, $trail) = ($1, $2, $3);
+                               $match = chop_str($match, 70, 5, 'center');
+                               my $contextlen = int((80 - length($match))/2);
+                               $contextlen = 30 if ($contextlen > 30);
+                               $lead  = chop_str($lead,  $contextlen, 10, 'left');
+                               $trail = chop_str($trail, $contextlen, 10, 'right');
+
+                               $lead  = esc_html($lead);
+                               $match = esc_html($match);
+                               $trail = esc_html($trail);
+
+                               print "$lead<span class=\"match\">$match</span>$trail<br />";
                        }
                }
                print "</td>\n" .
                      "<td class=\"link\">" .
                      $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
                      " | " .
+                     $cgi->a({-href => href(action=>"commitdiff", hash=>$co{'id'})}, "commitdiff") .
+                     " | " .
                      $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
                print "</td>\n" .
                      "</tr>\n";
@@ -3764,7 +4049,7 @@ sub git_summary {
        git_print_page_nav('summary','', $head);
 
        print "<div class=\"title\">&nbsp;</div>\n";
-       print "<table cellspacing=\"0\">\n" .
+       print "<table class=\"projects_list\">\n" .
              "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" .
              "<tr><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n";
        if (defined $cd{'rfc2822'}) {
@@ -3785,8 +4070,10 @@ sub git_summary {
 
        if (-s "$projectroot/$project/README.html") {
                if (open my $fd, "$projectroot/$project/README.html") {
-                       print "<div class=\"title\">readme</div>\n";
+                       print "<div class=\"title\">readme</div>\n" .
+                             "<div class=\"readme\">\n";
                        print $_ while (<$fd>);
+                       print "\n</div>\n"; # class="readme"
                        close $fd;
                }
        }
@@ -3838,7 +4125,7 @@ sub git_tag {
 
        git_print_header_div('commit', esc_html($tag{'name'}), $hash);
        print "<div class=\"title_text\">\n" .
-             "<table cellspacing=\"0\">\n" .
+             "<table class=\"object_header\">\n" .
              "<tr>\n" .
              "<td>object</td>\n" .
              "<td>" . $cgi->a({-class => "list", -href => href(action=>$tag{'type'}, hash=>$tag{'object'})},
@@ -3891,11 +4178,11 @@ sub git_blame2 {
                or die_error(undef, "Open git-blame failed");
        git_header_html();
        my $formats_nav =
-               $cgi->a({-href => href(action=>"blob", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
+               $cgi->a({-href => href(action=>"blob", -replay=>1)},
                        "blob") .
                " | " .
-               $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base, file_name=>$file_name)},
-                       "history") .
+               $cgi->a({-href => href(action=>"history", -replay=>1)},
+                       "history") .
                " | " .
                $cgi->a({-href => href(action=>"blame", file_name=>$file_name)},
                        "HEAD");
@@ -4097,6 +4384,7 @@ sub git_heads {
 }
 
 sub git_blob_plain {
+       my $type = shift;
        my $expires;
 
        if (!defined $hash) {
@@ -4112,13 +4400,13 @@ sub git_blob_plain {
                $expires = "+1d";
        }
 
-       my $type = shift;
        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
-               or die_error(undef, "Couldn't cat $file_name, $hash");
+               or die_error(undef, "Open git-cat-file blob '$hash' failed");
 
-       $type ||= blob_mimetype($fd, $file_name);
+       # content-type (can include charset)
+       $type = blob_contenttype($fd, $file_name, $type);
 
-       # save as filename, even when no $file_name is given
+       # "save as" filename, even when no $file_name is given
        my $save_as = "$hash";
        if (defined $file_name) {
                $save_as = $file_name;
@@ -4127,9 +4415,9 @@ sub git_blob_plain {
        }
 
        print $cgi->header(
-               -type => "$type",
-               -expires=>$expires,
-               -content_disposition => 'inline; filename="' . "$save_as" . '"');
+               -type => $type,
+               -expires => $expires,
+               -content_disposition => 'inline; filename="' . $save_as . '"');
        undef $/;
        binmode STDOUT, ':raw';
        print <$fd>;
@@ -4158,7 +4446,7 @@ sub git_blob {
        open my $fd, "-|", git_cmd(), "cat-file", "blob", $hash
                or die_error(undef, "Couldn't cat $file_name, $hash");
        my $mimetype = blob_mimetype($fd, $file_name);
-       if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)!) {
+       if ($mimetype !~ m!^(?:text/|image/(?:gif|png|jpeg)$)! && -B $fd) {
                close $fd;
                return git_blob_plain($mimetype);
        }
@@ -4171,18 +4459,15 @@ sub git_blob {
                if (defined $file_name) {
                        if ($have_blame) {
                                $formats_nav .=
-                                       $cgi->a({-href => href(action=>"blame", hash_base=>$hash_base,
-                                                              hash=>$hash, file_name=>$file_name)},
+                                       $cgi->a({-href => href(action=>"blame", -replay=>1)},
                                                "blame") .
                                        " | ";
                        }
                        $formats_nav .=
-                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
-                                                      hash=>$hash, file_name=>$file_name)},
+                               $cgi->a({-href => href(action=>"history", -replay=>1)},
                                        "history") .
                                " | " .
-                               $cgi->a({-href => href(action=>"blob_plain",
-                                                      hash=>$hash, file_name=>$file_name)},
+                               $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
                                        "raw") .
                                " | " .
                                $cgi->a({-href => href(action=>"blob",
@@ -4190,7 +4475,8 @@ sub git_blob {
                                        "HEAD");
                } else {
                        $formats_nav .=
-                               $cgi->a({-href => href(action=>"blob_plain", hash=>$hash)}, "raw");
+                               $cgi->a({-href => href(action=>"blob_plain", -replay=>1)},
+                                       "raw");
                }
                git_print_page_nav('','', $hash_base,$co{'tree'},$hash_base, $formats_nav);
                git_print_header_div('commit', esc_html($co{'title'}), $hash_base);
@@ -4201,16 +4487,7 @@ sub git_blob {
        }
        git_print_page_path($file_name, "blob", $hash_base);
        print "<div class=\"page_body\">\n";
-       if ($mimetype =~ m!^text/!) {
-               my $nr;
-               while (my $line = <$fd>) {
-                       chomp $line;
-                       $nr++;
-                       $line = untabify($line);
-                       printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
-                              $nr, $nr, $nr, esc_html($line, -nbsp=>1);
-               }
-       } elsif ($mimetype =~ m!^image/!) {
+       if ($mimetype =~ m!^image/!) {
                print qq!<img type="$mimetype"!;
                if ($file_name) {
                        print qq! alt="$file_name" title="$file_name"!;
@@ -4219,6 +4496,15 @@ sub git_blob {
                      href(action=>"blob_plain", hash=>$hash,
                           hash_base=>$hash_base, file_name=>$file_name) .
                      qq!" />\n!;
+       } else {
+               my $nr;
+               while (my $line = <$fd>) {
+                       chomp $line;
+                       $nr++;
+                       $line = untabify($line);
+                       printf "<div class=\"pre\"><a id=\"l%i\" href=\"#l%i\" class=\"linenr\">%4i</a> %s</div>\n",
+                              $nr, $nr, $nr, esc_html($line, -nbsp=>1);
+               }
        }
        close $fd
                or print "Reading blob failed.\n";
@@ -4253,8 +4539,7 @@ sub git_tree {
                my @views_nav = ();
                if (defined $file_name) {
                        push @views_nav,
-                               $cgi->a({-href => href(action=>"history", hash_base=>$hash_base,
-                                                      hash=>$hash, file_name=>$file_name)},
+                               $cgi->a({-href => href(action=>"history", -replay=>1)},
                                        "history"),
                                $cgi->a({-href => href(action=>"tree",
                                                       hash_base=>"HEAD", file_name=>$file_name)},
@@ -4281,7 +4566,7 @@ sub git_tree {
        }
        git_print_page_path($file_name, 'tree', $hash_base);
        print "<div class=\"page_body\">\n";
-       print "<table cellspacing=\"0\">\n";
+       print "<table class=\"tree\">\n";
        my $alternate = 1;
        # '..' (top directory) link if possible
        if (defined $hash_base &&
@@ -4348,7 +4633,6 @@ sub git_snapshot {
                $hash = git_get_head_hash($project);
        }
 
-       my $git_command = git_cmd_str();
        my $name = $project;
        $name =~ s,([^/])/*\.git$,$1,;
        $name = basename($name);
@@ -4356,11 +4640,12 @@ sub git_snapshot {
        $name =~ s/\047/\047\\\047\047/g;
        my $cmd;
        $filename .= "-$hash$known_snapshot_formats{$format}{'suffix'}";
-       $cmd = "$git_command archive " .
-               "--format=$known_snapshot_formats{$format}{'format'} " .
-               "--prefix=\'$name\'/ $hash";
+       $cmd = quote_command(
+               git_cmd(), 'archive',
+               "--format=$known_snapshot_formats{$format}{'format'}",
+               "--prefix=$name/", $hash);
        if (exists $known_snapshot_formats{$format}{'compressor'}) {
-               $cmd .= ' | ' . join ' ', @{$known_snapshot_formats{$format}{'compressor'}};
+               $cmd .= ' | ' . quote_command(@{$known_snapshot_formats{$format}{'compressor'}});
        }
 
        print $cgi->header(
@@ -4388,7 +4673,7 @@ sub git_log {
 
        my @commitlist = parse_commits($hash, 101, (100 * $page));
 
-       my $paging_nav = format_paging_nav('log', $hash, $head, $page, (100 * ($page+1)));
+       my $paging_nav = format_paging_nav('log', $hash, $head, $page, $#commitlist >= 100);
 
        git_header_html();
        git_print_page_nav('log','', $hash,undef,undef, $paging_nav);
@@ -4428,7 +4713,7 @@ sub git_log {
        }
        if ($#commitlist >= 100) {
                print "<div class=\"page_nav\">\n";
-               print $cgi->a({-href => href(action=>"log", hash=>$hash, page=>$page+1),
+               print $cgi->a({-href => href(-replay=>1, page=>$page+1),
                               -accesskey => "n", -title => "Alt-n"}, "next");
                print "</div>\n";
        }
@@ -4503,7 +4788,7 @@ sub git_commit {
                git_print_header_div('tree', esc_html($co{'title'}) . $ref, $co{'tree'}, $hash);
        }
        print "<div class=\"title_text\">\n" .
-             "<table cellspacing=\"0\">\n";
+             "<table class=\"object_header\">\n";
        print "<tr><td>author</td><td>" . esc_html($co{'author'}) . "</td></tr>\n".
              "<tr>" .
              "<td></td><td> $ad{'rfc2822'}";
@@ -4573,8 +4858,8 @@ sub git_object {
        if ($hash || ($hash_base && !defined $file_name)) {
                my $object_id = $hash || $hash_base;
 
-               my $git_command = git_cmd_str();
-               open my $fd, "-|", "$git_command cat-file -t $object_id 2>/dev/null"
+               open my $fd, "-|", quote_command(
+                       git_cmd(), 'cat-file', '-t', $object_id) . ' 2> /dev/null'
                        or die_error('404 Not Found', "Object does not exist");
                $type = <$fd>;
                chomp $type;
@@ -4660,8 +4945,8 @@ sub git_blobdiff {
                }
 
                %diffinfo = parse_difftree_raw_line($difftree[0]);
-               $file_parent ||= $diffinfo{'from_file'} || $file_name || $diffinfo{'file'};
-               $file_name   ||= $diffinfo{'to_file'}   || $diffinfo{'file'};
+               $file_parent ||= $diffinfo{'from_file'} || $file_name;
+               $file_name   ||= $diffinfo{'to_file'};
 
                $hash_parent ||= $diffinfo{'from_id'};
                $hash        ||= $diffinfo{'to_id'};
@@ -4722,10 +5007,7 @@ sub git_blobdiff {
        # header
        if ($format eq 'html') {
                my $formats_nav =
-                       $cgi->a({-href => href(action=>"blobdiff_plain",
-                                              hash=>$hash, hash_parent=>$hash_parent,
-                                              hash_base=>$hash_base, hash_parent_base=>$hash_parent_base,
-                                              file_name=>$file_name, file_parent=>$file_parent)},
+                       $cgi->a({-href => href(action=>"blobdiff_plain", -replay=>1)},
                                "raw");
                git_header_html(undef, $expires);
                if (defined $hash_base && (my %co = parse_commit($hash_base))) {
@@ -4799,8 +5081,7 @@ sub git_commitdiff {
        my $formats_nav;
        if ($format eq 'html') {
                $formats_nav =
-                       $cgi->a({-href => href(action=>"commitdiff_plain",
-                                              hash=>$hash, hash_parent=>$hash_parent)},
+                       $cgi->a({-href => href(action=>"commitdiff_plain", -replay=>1)},
                                "raw");
 
                if (defined $hash_parent &&
@@ -4923,16 +5204,15 @@ sub git_commitdiff {
                        -expires => $expires,
                        -content_disposition => 'inline; filename="' . "$filename" . '"');
                my %ad = parse_date($co{'author_epoch'}, $co{'author_tz'});
-               print <<TEXT;
-From: $co{'author'}
-Date: $ad{'rfc2822'} ($ad{'tz_local'})
-Subject: $co{'title'}
-TEXT
+               print "From: " . to_utf8($co{'author'}) . "\n";
+               print "Date: $ad{'rfc2822'} ($ad{'tz_local'})\n";
+               print "Subject: " . to_utf8($co{'title'}) . "\n";
+
                print "X-Git-Tag: $tagname\n" if $tagname;
                print "X-Git-Url: " . $cgi->self_url() . "\n\n";
 
                foreach my $line (@{$co{'comment'}}) {
-                       print "$line\n";
+                       print to_utf8($line) . "\n";
                }
                print "---\n\n";
        }
@@ -4979,14 +5259,26 @@ sub git_history {
        my $refs = git_get_references();
        my $limit = sprintf("--max-count=%i", (100 * ($page+1)));
 
+       my @commitlist = parse_commits($hash_base, 101, (100 * $page),
+                                      $file_name, "--full-history");
+       if (!@commitlist) {
+               die_error('404 Not Found', "No such file or directory on given branch");
+       }
+
        if (!defined $hash && defined $file_name) {
-               $hash = git_get_hash_by_path($hash_base, $file_name);
+               # some commits could have deleted file in question,
+               # and not have it in tree, but one of them has to have it
+               for (my $i = 0; $i <= @commitlist; $i++) {
+                       $hash = git_get_hash_by_path($commitlist[$i]{'id'}, $file_name);
+                       last if defined $hash;
+               }
        }
        if (defined $hash) {
                $ftype = git_get_type($hash);
        }
-
-       my @commitlist = parse_commits($hash_base, 101, (100 * $page), "--full-history", $file_name);
+       if (!defined $ftype) {
+               die_error(undef, "Unknown type of object");
+       }
 
        my $paging_nav = '';
        if ($page > 0) {
@@ -4995,27 +5287,20 @@ sub git_history {
                                               file_name=>$file_name)},
                                "first");
                $paging_nav .= " &sdot; " .
-                       $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
-                                              file_name=>$file_name, page=>$page-1),
+                       $cgi->a({-href => href(-replay=>1, page=>$page-1),
                                 -accesskey => "p", -title => "Alt-p"}, "prev");
        } else {
                $paging_nav .= "first";
                $paging_nav .= " &sdot; prev";
        }
-       if ($#commitlist >= 100) {
-               $paging_nav .= " &sdot; " .
-                       $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
-                                              file_name=>$file_name, page=>$page+1),
-                                -accesskey => "n", -title => "Alt-n"}, "next");
-       } else {
-               $paging_nav .= " &sdot; next";
-       }
        my $next_link = '';
        if ($#commitlist >= 100) {
                $next_link =
-                       $cgi->a({-href => href(action=>"history", hash=>$hash, hash_base=>$hash_base,
-                                              file_name=>$file_name, page=>$page+1),
+                       $cgi->a({-href => href(-replay=>1, page=>$page+1),
                                 -accesskey => "n", -title => "Alt-n"}, "next");
+               $paging_nav .= " &sdot; $next_link";
+       } else {
+               $paging_nav .= " &sdot; next";
        }
 
        git_header_html();
@@ -5075,40 +5360,36 @@ sub git_search {
                } elsif ($searchtype eq 'committer') {
                        $greptype = "--committer=";
                }
-               $greptype .= $search_regexp;
-               my @commitlist = parse_commits($hash, 101, (100 * $page), $greptype);
+               $greptype .= $searchtext;
+               my @commitlist = parse_commits($hash, 101, (100 * $page), undef,
+                                              $greptype, '--regexp-ignore-case',
+                                              $search_use_regexp ? '--extended-regexp' : '--fixed-strings');
 
                my $paging_nav = '';
                if ($page > 0) {
                        $paging_nav .=
                                $cgi->a({-href => href(action=>"search", hash=>$hash,
-                                                      searchtext=>$searchtext, searchtype=>$searchtype)},
+                                                      searchtext=>$searchtext,
+                                                      searchtype=>$searchtype)},
                                        "first");
                        $paging_nav .= " &sdot; " .
-                               $cgi->a({-href => href(action=>"search", hash=>$hash,
-                                                      searchtext=>$searchtext, searchtype=>$searchtype,
-                                                      page=>$page-1),
+                               $cgi->a({-href => href(-replay=>1, page=>$page-1),
                                         -accesskey => "p", -title => "Alt-p"}, "prev");
                } else {
                        $paging_nav .= "first";
                        $paging_nav .= " &sdot; prev";
                }
+               my $next_link = '';
                if ($#commitlist >= 100) {
-                       $paging_nav .= " &sdot; " .
-                               $cgi->a({-href => href(action=>"search", hash=>$hash,
-                                                      searchtext=>$searchtext, searchtype=>$searchtype,
-                                                      page=>$page+1),
+                       $next_link =
+                               $cgi->a({-href => href(-replay=>1, page=>$page+1),
                                         -accesskey => "n", -title => "Alt-n"}, "next");
+                       $paging_nav .= " &sdot; $next_link";
                } else {
                        $paging_nav .= " &sdot; next";
                }
-               my $next_link = '';
+
                if ($#commitlist >= 100) {
-                       $next_link =
-                               $cgi->a({-href => href(action=>"search", hash=>$hash,
-                                                      searchtext=>$searchtext, searchtype=>$searchtype,
-                                                      page=>$page+1),
-                                        -accesskey => "n", -title => "Alt-n"}, "next");
                }
 
                git_print_page_nav('','', $hash,$co{'tree'},$hash, $paging_nav);
@@ -5120,52 +5401,22 @@ sub git_search {
                git_print_page_nav('','', $hash,$co{'tree'},$hash);
                git_print_header_div('commit', esc_html($co{'title'}), $hash);
 
-               print "<table cellspacing=\"0\">\n";
+               print "<table class=\"pickaxe search\">\n";
                my $alternate = 1;
                $/ = "\n";
-               my $git_command = git_cmd_str();
-               my $searchqtext = $searchtext;
-               $searchqtext =~ s/'/'\\''/;
-               open my $fd, "-|", "$git_command rev-list $hash | " .
-                       "$git_command diff-tree -r --stdin -S\'$searchqtext\'";
+               open my $fd, '-|', git_cmd(), '--no-pager', 'log', @diff_opts,
+                       '--pretty=format:%H', '--no-abbrev', '--raw', "-S$searchtext",
+                       ($search_use_regexp ? '--pickaxe-regex' : ());
                undef %co;
                my @files;
                while (my $line = <$fd>) {
-                       if (%co && $line =~ m/^:([0-7]{6}) ([0-7]{6}) ([0-9a-fA-F]{40}) ([0-9a-fA-F]{40}) (.)\t(.*)$/) {
-                               my %set;
-                               $set{'file'} = $6;
-                               $set{'from_id'} = $3;
-                               $set{'to_id'} = $4;
-                               $set{'id'} = $set{'to_id'};
-                               if ($set{'id'} =~ m/0{40}/) {
-                                       $set{'id'} = $set{'from_id'};
-                               }
-                               if ($set{'id'} =~ m/0{40}/) {
-                                       next;
-                               }
-                               push @files, \%set;
-                       } elsif ($line =~ m/^([0-9a-fA-F]{40})$/){
+                       chomp $line;
+                       next unless $line;
+
+                       my %set = parse_difftree_raw_line($line);
+                       if (defined $set{'commit'}) {
+                               # finish previous commit
                                if (%co) {
-                                       if ($alternate) {
-                                               print "<tr class=\"dark\">\n";
-                                       } else {
-                                               print "<tr class=\"light\">\n";
-                                       }
-                                       $alternate ^= 1;
-                                       print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
-                                             "<td><i>" . esc_html(chop_str($co{'author_name'}, 15, 5)) . "</i></td>\n" .
-                                             "<td>" .
-                                             $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
-                                                     -class => "list subject"},
-                                                     esc_html(chop_str($co{'title'}, 50)) . "<br/>");
-                                       while (my $setref = shift @files) {
-                                               my %set = %$setref;
-                                               print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
-                                                                            hash=>$set{'id'}, file_name=>$set{'file'}),
-                                                             -class => "list"},
-                                                             "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
-                                                     "<br/>\n";
-                                       }
                                        print "</td>\n" .
                                              "<td class=\"link\">" .
                                              $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
@@ -5174,11 +5425,44 @@ sub git_search {
                                        print "</td>\n" .
                                              "</tr>\n";
                                }
-                               %co = parse_commit($1);
+
+                               if ($alternate) {
+                                       print "<tr class=\"dark\">\n";
+                               } else {
+                                       print "<tr class=\"light\">\n";
+                               }
+                               $alternate ^= 1;
+                               %co = parse_commit($set{'commit'});
+                               my $author = chop_and_escape_str($co{'author_name'}, 15, 5);
+                               print "<td title=\"$co{'age_string_age'}\"><i>$co{'age_string_date'}</i></td>\n" .
+                                     "<td><i>$author</i></td>\n" .
+                                     "<td>" .
+                                     $cgi->a({-href => href(action=>"commit", hash=>$co{'id'}),
+                                             -class => "list subject"},
+                                             chop_and_escape_str($co{'title'}, 50) . "<br/>");
+                       } elsif (defined $set{'to_id'}) {
+                               next if ($set{'to_id'} =~ m/^0{40}$/);
+
+                               print $cgi->a({-href => href(action=>"blob", hash_base=>$co{'id'},
+                                                            hash=>$set{'to_id'}, file_name=>$set{'to_file'}),
+                                             -class => "list"},
+                                             "<span class=\"match\">" . esc_path($set{'file'}) . "</span>") .
+                                     "<br/>\n";
                        }
                }
                close $fd;
 
+               # finish last commit (warning: repetition!)
+               if (%co) {
+                       print "</td>\n" .
+                             "<td class=\"link\">" .
+                             $cgi->a({-href => href(action=>"commit", hash=>$co{'id'})}, "commit") .
+                             " | " .
+                             $cgi->a({-href => href(action=>"tree", hash=>$co{'tree'}, hash_base=>$co{'id'})}, "tree");
+                       print "</td>\n" .
+                             "</tr>\n";
+               }
+
                print "</table>\n";
        }
 
@@ -5186,11 +5470,13 @@ sub git_search {
                git_print_page_nav('','', $hash,$co{'tree'},$hash);
                git_print_header_div('commit', esc_html($co{'title'}), $hash);
 
-               print "<table cellspacing=\"0\">\n";
+               print "<table class=\"grep_search\">\n";
                my $alternate = 1;
                my $matches = 0;
                $/ = "\n";
-               open my $fd, "-|", git_cmd(), 'grep', '-n', '-i', '-E', $searchtext, $co{'tree'};
+               open my $fd, "-|", git_cmd(), 'grep', '-n',
+                       $search_use_regexp ? ('-E', '-i') : '-F',
+                       $searchtext, $co{'tree'};
                my $lastfile = '';
                while (my $line = <$fd>) {
                        chomp $line;
@@ -5220,7 +5506,7 @@ sub git_search {
                                print "<div class=\"binary\">Binary file</div>\n";
                        } else {
                                $ltext = untabify($ltext);
-                               if ($ltext =~ m/^(.*)($searchtext)(.*)$/i) {
+                               if ($ltext =~ m/^(.*)($search_regexp)(.*)$/i) {
                                        $ltext = esc_html($1, -nbsp=>1);
                                        $ltext .= '<span class="match">';
                                        $ltext .= esc_html($2, -nbsp=>1);
@@ -5255,27 +5541,31 @@ sub git_search_help {
        git_header_html();
        git_print_page_nav('','', $hash,$hash,$hash);
        print <<EOT;
+<p><strong>Pattern</strong> is by default a normal string that is matched precisely (but without
+regard to case, except in the case of pickaxe). However, when you check the <em>re</em> checkbox,
+the pattern entered is recognized as the POSIX extended
+<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> (also case
+insensitive).</p>
 <dl>
 <dt><b>commit</b></dt>
-<dd>The commit messages and authorship information will be scanned for the given string.</dd>
+<dd>The commit messages and authorship information will be scanned for the given pattern.</dd>
 EOT
        my ($have_grep) = gitweb_check_feature('grep');
        if ($have_grep) {
                print <<EOT;
 <dt><b>grep</b></dt>
 <dd>All files in the currently selected tree (HEAD unless you are explicitly browsing
-    a different one) are searched for the given
-<a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a>
-(POSIX extended) and the matches are listed. On large
-trees, this search can take a while and put some strain on the server, so please use it with
-some consideration.</dd>
+    a different one) are searched for the given pattern. On large trees, this search can take
+a while and put some strain on the server, so please use it with some consideration. Note that
+due to git-grep peculiarity, currently if regexp mode is turned off, the matches are
+case-sensitive.</dd>
 EOT
        }
        print <<EOT;
 <dt><b>author</b></dt>
-<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given string.</dd>
+<dd>Name and e-mail of the change author and date of birth of the patch will be scanned for the given pattern.</dd>
 <dt><b>committer</b></dt>
-<dd>Name and e-mail of the committer and date of commit will be scanned for the given string.</dd>
+<dd>Name and e-mail of the committer and date of commit will be scanned for the given pattern.</dd>
 EOT
        my ($have_pickaxe) = gitweb_check_feature('pickaxe');
        if ($have_pickaxe) {
@@ -5283,7 +5573,8 @@ EOT
 <dt><b>pickaxe</b></dt>
 <dd>All commits that caused the string to appear or disappear from any file (changes that
 added, removed or "modified" the string) will be listed. This search can take a while and
-takes a lot of strain on the server, so please use it wisely.</dd>
+takes a lot of strain on the server, so please use it wisely. Note that since you may be
+interested even in changes just changing the case as well, this search is case sensitive.</dd>
 EOT
        }
        print "</dl>\n";
@@ -5302,11 +5593,11 @@ sub git_shortlog {
 
        my @commitlist = parse_commits($hash, 101, (100 * $page));
 
-       my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, (100 * ($page+1)));
+       my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100);
        my $next_link = '';
        if ($#commitlist >= 100) {
                $next_link =
-                       $cgi->a({-href => href(action=>"shortlog", hash=>$hash, page=>$page+1),
+                       $cgi->a({-href => href(-replay=>1, page=>$page+1),
                                 -accesskey => "n", -title => "Alt-n"}, "next");
        }
 
@@ -5334,7 +5625,7 @@ sub git_feed {
 
        # log/feed of current (HEAD) branch, log of given branch, history of file/directory
        my $head = $hash || 'HEAD';
-       my @commitlist = parse_commits($head, 150, 0, undef, $file_name);
+       my @commitlist = parse_commits($head, 150, 0, $file_name);
 
        my %latest_commit;
        my %latest_date;
@@ -5454,7 +5745,7 @@ XML
                        or next;
 
                # print element (entry, item)
-               my $co_url = href(-full=>1, action=>"commit", hash=>$commit);
+               my $co_url = href(-full=>1, action=>"commitdiff", hash=>$commit);
                if ($format eq 'rss') {
                        print "<item>\n" .
                              "<title>" . esc_html($co{'title'}) . "</title>\n" .