git-gui: use existing interface to query a path's attribute
[git] / lib / diff.tcl
1 # git-gui diff viewer
2 # Copyright (C) 2006, 2007 Shawn Pearce
3
4 proc apply_tab_size {{firsttab {}}} {
5         global have_tk85 repo_config ui_diff
6
7         set w [font measure font_diff "0"]
8         if {$have_tk85 && $firsttab != 0} {
9                 $ui_diff configure -tabs [list [expr {$firsttab * $w}] [expr {($firsttab + $repo_config(gui.tabsize)) * $w}]]
10         } elseif {$have_tk85 || $repo_config(gui.tabsize) != 8} {
11                 $ui_diff configure -tabs [expr {$repo_config(gui.tabsize) * $w}]
12         } else {
13                 $ui_diff configure -tabs {}
14         }
15 }
16
17 proc clear_diff {} {
18         global ui_diff current_diff_path current_diff_header
19         global ui_index ui_workdir
20
21         $ui_diff conf -state normal
22         $ui_diff delete 0.0 end
23         $ui_diff conf -state disabled
24
25         set current_diff_path {}
26         set current_diff_header {}
27
28         $ui_index tag remove in_diff 0.0 end
29         $ui_workdir tag remove in_diff 0.0 end
30 }
31
32 proc reshow_diff {{after {}}} {
33         global file_states file_lists
34         global current_diff_path current_diff_side
35         global ui_diff
36
37         set p $current_diff_path
38         if {$p eq {}} {
39                 # No diff is being shown.
40         } elseif {$current_diff_side eq {}} {
41                 clear_diff
42         } elseif {[catch {set s $file_states($p)}]
43                 || [lsearch -sorted -exact $file_lists($current_diff_side) $p] == -1} {
44
45                 if {[find_next_diff $current_diff_side $p {} {[^O]}]} {
46                         next_diff $after
47                 } else {
48                         clear_diff
49                 }
50         } else {
51                 set save_pos [lindex [$ui_diff yview] 0]
52                 show_diff $p $current_diff_side {} $save_pos $after
53         }
54 }
55
56 proc force_diff_encoding {enc} {
57         global current_diff_path
58
59         if {$current_diff_path ne {}} {
60                 force_path_encoding $current_diff_path $enc
61                 reshow_diff
62         }
63 }
64
65 proc handle_empty_diff {} {
66         global current_diff_path file_states file_lists
67         global diff_empty_count
68
69         set path $current_diff_path
70         set s $file_states($path)
71         if {[lindex $s 0] ne {_M} || [has_textconv $path]} return
72
73         # Prevent infinite rescan loops
74         incr diff_empty_count
75         if {$diff_empty_count > 1} return
76
77         info_popup [mc "No differences detected.
78
79 %s has no changes.
80
81 The modification date of this file was updated by another application, but the content within the file was not changed.
82
83 A rescan will be automatically started to find other files which may have the same state." [short_path $path]]
84
85         clear_diff
86         display_file $path __
87         rescan ui_ready 0
88 }
89
90 proc show_diff {path w {lno {}} {scroll_pos {}} {callback {}}} {
91         global file_states file_lists
92         global is_3way_diff is_conflict_diff diff_active repo_config
93         global ui_diff ui_index ui_workdir
94         global current_diff_path current_diff_side current_diff_header
95         global current_diff_queue
96
97         if {$diff_active || ![lock_index read]} return
98
99         clear_diff
100         if {$lno == {}} {
101                 set lno [lsearch -sorted -exact $file_lists($w) $path]
102                 if {$lno >= 0} {
103                         incr lno
104                 }
105         }
106         if {$lno >= 1} {
107                 $w tag add in_diff $lno.0 [expr {$lno + 1}].0
108                 $w see $lno.0
109         }
110
111         set s $file_states($path)
112         set m [lindex $s 0]
113         set is_conflict_diff 0
114         set current_diff_path $path
115         set current_diff_side $w
116         set current_diff_queue {}
117         ui_status [mc "Loading diff of %s..." [escape_path $path]]
118
119         set cont_info [list $scroll_pos $callback]
120
121         apply_tab_size 0
122
123         if {[string first {U} $m] >= 0} {
124                 merge_load_stages $path [list show_unmerged_diff $cont_info]
125         } elseif {$m eq {_O}} {
126                 show_other_diff $path $w $m $cont_info
127         } else {
128                 start_show_diff $cont_info
129         }
130
131         global current_diff_path selected_paths
132         set selected_paths($current_diff_path) 1
133 }
134
135 proc show_unmerged_diff {cont_info} {
136         global current_diff_path current_diff_side
137         global merge_stages ui_diff is_conflict_diff
138         global current_diff_queue
139
140         if {$merge_stages(2) eq {}} {
141                 set is_conflict_diff 1
142                 lappend current_diff_queue \
143                         [list [mc "LOCAL: deleted\nREMOTE:\n"] d= \
144                             [list ":1:$current_diff_path" ":3:$current_diff_path"]]
145         } elseif {$merge_stages(3) eq {}} {
146                 set is_conflict_diff 1
147                 lappend current_diff_queue \
148                         [list [mc "REMOTE: deleted\nLOCAL:\n"] d= \
149                             [list ":1:$current_diff_path" ":2:$current_diff_path"]]
150         } elseif {[lindex $merge_stages(1) 0] eq {120000}
151                 || [lindex $merge_stages(2) 0] eq {120000}
152                 || [lindex $merge_stages(3) 0] eq {120000}} {
153                 set is_conflict_diff 1
154                 lappend current_diff_queue \
155                         [list [mc "LOCAL:\n"] d= \
156                             [list ":1:$current_diff_path" ":2:$current_diff_path"]]
157                 lappend current_diff_queue \
158                         [list [mc "REMOTE:\n"] d= \
159                             [list ":1:$current_diff_path" ":3:$current_diff_path"]]
160         } else {
161                 start_show_diff $cont_info
162                 return
163         }
164
165         advance_diff_queue $cont_info
166 }
167
168 proc advance_diff_queue {cont_info} {
169         global current_diff_queue ui_diff
170
171         set item [lindex $current_diff_queue 0]
172         set current_diff_queue [lrange $current_diff_queue 1 end]
173
174         $ui_diff conf -state normal
175         $ui_diff insert end [lindex $item 0] [lindex $item 1]
176         $ui_diff conf -state disabled
177
178         start_show_diff $cont_info [lindex $item 2]
179 }
180
181 proc show_other_diff {path w m cont_info} {
182         global file_states file_lists
183         global is_3way_diff diff_active repo_config
184         global ui_diff ui_index ui_workdir
185         global current_diff_path current_diff_side current_diff_header
186
187         # - Git won't give us the diff, there's nothing to compare to!
188         #
189         if {$m eq {_O}} {
190                 set max_sz 100000
191                 set type unknown
192                 if {[catch {
193                                 set type [file type $path]
194                                 switch -- $type {
195                                 directory {
196                                         set type submodule
197                                         set content {}
198                                         set sz 0
199                                 }
200                                 link {
201                                         set content [file readlink $path]
202                                         set sz [string length $content]
203                                 }
204                                 file {
205                                         set fd [open $path r]
206                                         fconfigure $fd \
207                                                 -eofchar {} \
208                                                 -encoding [get_path_encoding $path]
209                                         set content [read $fd $max_sz]
210                                         close $fd
211                                         set sz [file size $path]
212                                 }
213                                 default {
214                                         error "'$type' not supported"
215                                 }
216                                 }
217                         } err ]} {
218                         set diff_active 0
219                         unlock_index
220                         ui_status [mc "Unable to display %s" [escape_path $path]]
221                         error_popup [strcat [mc "Error loading file:"] "\n\n$err"]
222                         return
223                 }
224                 $ui_diff conf -state normal
225                 if {$type eq {submodule}} {
226                         $ui_diff insert end \
227                                 "* [mc "Git Repository (subproject)"]\n" \
228                                 d_info
229                 } elseif {![catch {set type [exec file $path]}]} {
230                         set n [string length $path]
231                         if {[string equal -length $n $path $type]} {
232                                 set type [string range $type $n end]
233                                 regsub {^:?\s*} $type {} type
234                         }
235                         $ui_diff insert end "* $type\n" d_info
236                 }
237                 if {[string first "\0" $content] != -1} {
238                         $ui_diff insert end \
239                                 [mc "* Binary file (not showing content)."] \
240                                 d_info
241                 } else {
242                         if {$sz > $max_sz} {
243                                 $ui_diff insert end [mc \
244 "* Untracked file is %d bytes.
245 * Showing only first %d bytes.
246 " $sz $max_sz] d_info
247                         }
248                         $ui_diff insert end $content
249                         if {$sz > $max_sz} {
250                                 $ui_diff insert end [mc "
251 * Untracked file clipped here by %s.
252 * To see the entire file, use an external editor.
253 " [appname]] d_info
254                         }
255                 }
256                 $ui_diff conf -state disabled
257                 set diff_active 0
258                 unlock_index
259                 set scroll_pos [lindex $cont_info 0]
260                 if {$scroll_pos ne {}} {
261                         update
262                         $ui_diff yview moveto $scroll_pos
263                 }
264                 ui_ready
265                 set callback [lindex $cont_info 1]
266                 if {$callback ne {}} {
267                         eval $callback
268                 }
269                 return
270         }
271 }
272
273 proc start_show_diff {cont_info {add_opts {}}} {
274         global file_states file_lists
275         global is_3way_diff is_submodule_diff diff_active repo_config
276         global ui_diff ui_index ui_workdir
277         global current_diff_path current_diff_side current_diff_header
278
279         set path $current_diff_path
280         set w $current_diff_side
281
282         set s $file_states($path)
283         set m [lindex $s 0]
284         set is_3way_diff 0
285         set is_submodule_diff 0
286         set diff_active 1
287         set current_diff_header {}
288         set conflict_size [gitattr $path conflict-marker-size 7]
289
290         set cmd [list]
291         if {$w eq $ui_index} {
292                 lappend cmd diff-index
293                 lappend cmd --cached
294                 if {[git-version >= "1.7.2"]} {
295                         lappend cmd --ignore-submodules=dirty
296                 }
297         } elseif {$w eq $ui_workdir} {
298                 if {[string first {U} $m] >= 0} {
299                         lappend cmd diff
300                 } else {
301                         lappend cmd diff-files
302                 }
303         }
304         if {![is_config_false gui.textconv] && [git-version >= 1.6.1]} {
305                 lappend cmd --textconv
306         }
307
308         if {[string match {160000 *} [lindex $s 2]]
309          || [string match {160000 *} [lindex $s 3]]} {
310                 set is_submodule_diff 1
311
312                 if {[git-version >= "1.6.6"]} {
313                         lappend cmd --submodule
314                 }
315         }
316
317         lappend cmd -p
318         lappend cmd --color
319         set cmd [concat $cmd $repo_config(gui.diffopts)]
320         if {$repo_config(gui.diffcontext) >= 1} {
321                 lappend cmd "-U$repo_config(gui.diffcontext)"
322         }
323         if {$w eq $ui_index} {
324                 lappend cmd [PARENT]
325         }
326         if {$add_opts ne {}} {
327                 eval lappend cmd $add_opts
328         } else {
329                 lappend cmd --
330                 lappend cmd $path
331         }
332
333         if {$is_submodule_diff && [git-version < "1.6.6"]} {
334                 if {$w eq $ui_index} {
335                         set cmd [list submodule summary --cached -- $path]
336                 } else {
337                         set cmd [list submodule summary --files -- $path]
338                 }
339         }
340
341         if {[catch {set fd [eval git_read --nice $cmd]} err]} {
342                 set diff_active 0
343                 unlock_index
344                 ui_status [mc "Unable to display %s" [escape_path $path]]
345                 error_popup [strcat [mc "Error loading diff:"] "\n\n$err"]
346                 return
347         }
348
349         set ::current_diff_inheader 1
350         fconfigure $fd \
351                 -blocking 0 \
352                 -encoding [get_path_encoding $path] \
353                 -translation lf
354         fileevent $fd readable [list read_diff $fd $conflict_size $cont_info]
355 }
356
357 proc parse_color_line {line} {
358         set start 0
359         set result ""
360         set markup [list]
361         set regexp {\033\[((?:\d+;)*\d+)?m}
362         set need_reset 0
363         while {[regexp -indices -start $start $regexp $line match code]} {
364                 foreach {begin end} $match break
365                 append result [string range $line $start [expr {$begin - 1}]]
366                 set pos [string length $result]
367                 set col [eval [linsert $code 0 string range $line]]
368                 set start [incr end]
369                 if {$col eq "0" || $col eq ""} {
370                         if {!$need_reset} continue
371                         set need_reset 0
372                 } else {
373                         set need_reset 1
374                 }
375                 lappend markup $pos $col
376         }
377         append result [string range $line $start end]
378         if {[llength $markup] < 4} {set markup {}}
379         return [list $result $markup]
380 }
381
382 proc read_diff {fd conflict_size cont_info} {
383         global ui_diff diff_active is_submodule_diff
384         global is_3way_diff is_conflict_diff current_diff_header
385         global current_diff_queue
386         global diff_empty_count
387
388         $ui_diff conf -state normal
389         while {[gets $fd line] >= 0} {
390                 foreach {line markup} [parse_color_line $line] break
391                 set line [string map {\033 ^} $line]
392
393                 set tags {}
394
395                 # -- Check for start of diff header.
396                 if {   [string match {diff --git *}      $line]
397                     || [string match {diff --cc *}       $line]
398                     || [string match {diff --combined *} $line]} {
399                         set ::current_diff_inheader 1
400                 }
401
402                 # -- Check for end of diff header (any hunk line will do this).
403                 #
404                 if {[regexp {^@@+ } $line]} {set ::current_diff_inheader 0}
405
406                 # -- Automatically detect if this is a 3 way diff.
407                 #
408                 if {[string match {@@@ *} $line]} {
409                         set is_3way_diff 1
410                         apply_tab_size 1
411                 }
412
413                 if {$::current_diff_inheader} {
414
415                         # -- These two lines stop a diff header and shouldn't be in there
416                         if {   [string match {Binary files * and * differ} $line]
417                             || [regexp {^\* Unmerged path }                $line]} {
418                                 set ::current_diff_inheader 0
419                         } else {
420                                 append current_diff_header $line "\n"
421                         }
422
423                         # -- Cleanup uninteresting diff header lines.
424                         #
425                         if {   [string match {diff --git *}      $line]
426                             || [string match {diff --cc *}       $line]
427                             || [string match {diff --combined *} $line]
428                             || [string match {--- *}             $line]
429                             || [string match {+++ *}             $line]
430                             || [string match {index *}           $line]} {
431                                 continue
432                         }
433
434                         # -- Name it symlink, not 120000
435                         #    Note, that the original line is in $current_diff_header
436                         regsub {^(deleted|new) file mode 120000} $line {\1 symlink} line
437
438                 } elseif {   $line eq {\ No newline at end of file}} {
439                         # -- Handle some special lines
440                 } elseif {$is_3way_diff} {
441                         set op [string range $line 0 1]
442                         switch -- $op {
443                         {  } {set tags {}}
444                         {@@} {set tags d_@}
445                         { +} {set tags d_s+}
446                         { -} {set tags d_s-}
447                         {+ } {set tags d_+s}
448                         {- } {set tags d_-s}
449                         {--} {set tags d_--}
450                         {++} {
451                                 set regexp [string map [list %conflict_size $conflict_size]\
452                                                                 {^\+\+([<>=]){%conflict_size}(?: |$)}]
453                                 if {[regexp $regexp $line _g op]} {
454                                         set is_conflict_diff 1
455                                         set line [string replace $line 0 1 {  }]
456                                         set tags d$op
457                                 } else {
458                                         set tags d_++
459                                 }
460                         }
461                         default {
462                                 puts "error: Unhandled 3 way diff marker: {$op}"
463                                 set tags {}
464                         }
465                         }
466                 } elseif {$is_submodule_diff} {
467                         if {$line == ""} continue
468                         if {[regexp {^Submodule } $line]} {
469                                 set tags d_info
470                         } elseif {[regexp {^\* } $line]} {
471                                 set line [string replace $line 0 1 {Submodule }]
472                                 set tags d_info
473                         } else {
474                                 set op [string range $line 0 2]
475                                 switch -- $op {
476                                 {  <} {set tags d_-}
477                                 {  >} {set tags d_+}
478                                 {  W} {set tags {}}
479                                 default {
480                                         puts "error: Unhandled submodule diff marker: {$op}"
481                                         set tags {}
482                                 }
483                                 }
484                         }
485                 } else {
486                         set op [string index $line 0]
487                         switch -- $op {
488                         { } {set tags {}}
489                         {@} {set tags d_@}
490                         {-} {set tags d_-}
491                         {+} {
492                                 set regexp [string map [list %conflict_size $conflict_size]\
493                                                                 {^\+([<>=]){%conflict_size}(?: |$)}]
494                                 if {[regexp $regexp $line _g op]} {
495                                         set is_conflict_diff 1
496                                         set tags d$op
497                                 } else {
498                                         set tags d_+
499                                 }
500                         }
501                         default {
502                                 puts "error: Unhandled 2 way diff marker: {$op}"
503                                 set tags {}
504                         }
505                         }
506                 }
507                 set mark [$ui_diff index "end - 1 line linestart"]
508                 $ui_diff insert end $line $tags
509                 if {[string index $line end] eq "\r"} {
510                         $ui_diff tag add d_cr {end - 2c}
511                 }
512                 $ui_diff insert end "\n" $tags
513
514                 foreach {posbegin colbegin posend colend} $markup {
515                         set prefix clr
516                         foreach style [lsort -integer [split $colbegin ";"]] {
517                                 if {$style eq "7"} {append prefix i; continue}
518                                 if {$style != 4 && ($style < 30 || $style > 47)} {continue}
519                                 set a "$mark linestart + $posbegin chars"
520                                 set b "$mark linestart + $posend chars"
521                                 catch {$ui_diff tag add $prefix$style $a $b}
522                         }
523                 }
524         }
525         $ui_diff conf -state disabled
526
527         if {[eof $fd]} {
528                 close $fd
529
530                 if {$current_diff_queue ne {}} {
531                         advance_diff_queue $cont_info
532                         return
533                 }
534
535                 set diff_active 0
536                 unlock_index
537                 set scroll_pos [lindex $cont_info 0]
538                 if {$scroll_pos ne {}} {
539                         update
540                         $ui_diff yview moveto $scroll_pos
541                 }
542                 ui_ready
543
544                 if {[$ui_diff index end] eq {2.0}} {
545                         handle_empty_diff
546                 } else {
547                         set diff_empty_count 0
548                 }
549
550                 set callback [lindex $cont_info 1]
551                 if {$callback ne {}} {
552                         eval $callback
553                 }
554         }
555 }
556
557 proc apply_or_revert_hunk {x y revert} {
558         global current_diff_path current_diff_header current_diff_side
559         global ui_diff ui_index file_states last_revert last_revert_enc
560
561         if {$current_diff_path eq {} || $current_diff_header eq {}} return
562         if {![lock_index apply_hunk]} return
563
564         set apply_cmd {apply --whitespace=nowarn}
565         set mi [lindex $file_states($current_diff_path) 0]
566         if {$current_diff_side eq $ui_index} {
567                 set failed_msg [mc "Failed to unstage selected hunk."]
568                 lappend apply_cmd --reverse --cached
569                 if {[string index $mi 0] ne {M}} {
570                         unlock_index
571                         return
572                 }
573         } else {
574                 if {$revert} {
575                         set failed_msg [mc "Failed to revert selected hunk."]
576                         lappend apply_cmd --reverse
577                 } else {
578                         set failed_msg [mc "Failed to stage selected hunk."]
579                         lappend apply_cmd --cached
580                 }
581
582                 if {[string index $mi 1] ne {M}} {
583                         unlock_index
584                         return
585                 }
586         }
587
588         set s_lno [lindex [split [$ui_diff index @$x,$y] .] 0]
589         set s_lno [$ui_diff search -backwards -regexp ^@@ $s_lno.0 0.0]
590         if {$s_lno eq {}} {
591                 unlock_index
592                 return
593         }
594
595         set e_lno [$ui_diff search -forwards -regexp ^@@ "$s_lno + 1 lines" end]
596         if {$e_lno eq {}} {
597                 set e_lno end
598         }
599
600         set wholepatch "$current_diff_header[$ui_diff get $s_lno $e_lno]"
601
602         if {[catch {
603                 set enc [get_path_encoding $current_diff_path]
604                 set p [eval git_write $apply_cmd]
605                 fconfigure $p -translation binary -encoding $enc
606                 puts -nonewline $p $wholepatch
607                 close $p} err]} {
608                 error_popup "$failed_msg\n\n$err"
609                 unlock_index
610                 return
611         }
612
613         if {$revert} {
614                 # Save a copy of this patch for undoing reverts.
615                 set last_revert $wholepatch
616                 set last_revert_enc $enc
617         }
618
619         $ui_diff conf -state normal
620         $ui_diff delete $s_lno $e_lno
621         $ui_diff conf -state disabled
622
623         # Check if the hunk was the last one in the file.
624         if {[$ui_diff get 1.0 end] eq "\n"} {
625                 set o _
626         } else {
627                 set o ?
628         }
629
630         # Update the status flags.
631         if {$revert} {
632                 set mi [string index $mi 0]$o
633         } elseif {$current_diff_side eq $ui_index} {
634                 set mi ${o}M
635         } elseif {[string index $mi 0] eq {_}} {
636                 set mi M$o
637         } else {
638                 set mi ?$o
639         }
640         unlock_index
641         display_file $current_diff_path $mi
642         # This should trigger shift to the next changed file
643         if {$o eq {_}} {
644                 reshow_diff
645         }
646 }
647
648 proc apply_or_revert_range_or_line {x y revert} {
649         global current_diff_path current_diff_header current_diff_side
650         global ui_diff ui_index file_states last_revert
651
652         set selected [$ui_diff tag nextrange sel 0.0]
653
654         if {$selected == {}} {
655                 set first [$ui_diff index "@$x,$y"]
656                 set last $first
657         } else {
658                 set first [lindex $selected 0]
659                 set last [lindex $selected 1]
660         }
661
662         set first_l [$ui_diff index "$first linestart"]
663         set last_l [$ui_diff index "$last lineend"]
664
665         if {$current_diff_path eq {} || $current_diff_header eq {}} return
666         if {![lock_index apply_hunk]} return
667
668         set apply_cmd {apply --whitespace=nowarn}
669         set mi [lindex $file_states($current_diff_path) 0]
670         if {$current_diff_side eq $ui_index} {
671                 set failed_msg [mc "Failed to unstage selected line."]
672                 set to_context {+}
673                 lappend apply_cmd --reverse --cached
674                 if {[string index $mi 0] ne {M}} {
675                         unlock_index
676                         return
677                 }
678         } else {
679                 if {$revert} {
680                         set failed_msg [mc "Failed to revert selected line."]
681                         set to_context {+}
682                         lappend apply_cmd --reverse
683                 } else {
684                         set failed_msg [mc "Failed to stage selected line."]
685                         set to_context {-}
686                         lappend apply_cmd --cached
687                 }
688
689                 if {[string index $mi 1] ne {M}} {
690                         unlock_index
691                         return
692                 }
693         }
694
695         set wholepatch {}
696
697         while {$first_l < $last_l} {
698                 set i_l [$ui_diff search -backwards -regexp ^@@ $first_l 0.0]
699                 if {$i_l eq {}} {
700                         # If there's not a @@ above, then the selected range
701                         # must have come before the first_l @@
702                         set i_l [$ui_diff search -regexp ^@@ $first_l $last_l]
703                 }
704                 if {$i_l eq {}} {
705                         unlock_index
706                         return
707                 }
708                 # $i_l is now at the beginning of a line
709
710                 # pick start line number from hunk header
711                 set hh [$ui_diff get $i_l "$i_l + 1 lines"]
712                 set hh [lindex [split $hh ,] 0]
713                 set hln [lindex [split $hh -] 1]
714                 set hln [lindex [split $hln " "] 0]
715
716                 # There is a special situation to take care of. Consider this
717                 # hunk:
718                 #
719                 #    @@ -10,4 +10,4 @@
720                 #     context before
721                 #    -old 1
722                 #    -old 2
723                 #    +new 1
724                 #    +new 2
725                 #     context after
726                 #
727                 # We used to keep the context lines in the order they appear in
728                 # the hunk. But then it is not possible to correctly stage only
729                 # "-old 1" and "+new 1" - it would result in this staged text:
730                 #
731                 #    context before
732                 #    old 2
733                 #    new 1
734                 #    context after
735                 #
736                 # (By symmetry it is not possible to *un*stage "old 2" and "new
737                 # 2".)
738                 #
739                 # We resolve the problem by introducing an asymmetry, namely,
740                 # when a "+" line is *staged*, it is moved in front of the
741                 # context lines that are generated from the "-" lines that are
742                 # immediately before the "+" block. That is, we construct this
743                 # patch:
744                 #
745                 #    @@ -10,4 +10,5 @@
746                 #     context before
747                 #    +new 1
748                 #     old 1
749                 #     old 2
750                 #     context after
751                 #
752                 # But we do *not* treat "-" lines that are *un*staged in a
753                 # special way.
754                 #
755                 # With this asymmetry it is possible to stage the change "old
756                 # 1" -> "new 1" directly, and to stage the change "old 2" ->
757                 # "new 2" by first staging the entire hunk and then unstaging
758                 # the change "old 1" -> "new 1".
759                 #
760                 # Applying multiple lines adds complexity to the special
761                 # situation.  The pre_context must be moved after the entire
762                 # first block of consecutive staged "+" lines, so that
763                 # staging both additions gives the following patch:
764                 #
765                 #    @@ -10,4 +10,6 @@
766                 #     context before
767                 #    +new 1
768                 #    +new 2
769                 #     old 1
770                 #     old 2
771                 #     context after
772
773                 # This is non-empty if and only if we are _staging_ changes;
774                 # then it accumulates the consecutive "-" lines (after
775                 # converting them to context lines) in order to be moved after
776                 # "+" change lines.
777                 set pre_context {}
778
779                 set n 0
780                 set m 0
781                 set i_l [$ui_diff index "$i_l + 1 lines"]
782                 set patch {}
783                 while {[$ui_diff compare $i_l < "end - 1 chars"] &&
784                        [$ui_diff get $i_l "$i_l + 2 chars"] ne {@@}} {
785                         set next_l [$ui_diff index "$i_l + 1 lines"]
786                         set c1 [$ui_diff get $i_l]
787                         if {[$ui_diff compare $first_l <= $i_l] &&
788                             [$ui_diff compare $i_l < $last_l] &&
789                             ($c1 eq {-} || $c1 eq {+})} {
790                                 # a line to stage/unstage
791                                 set ln [$ui_diff get $i_l $next_l]
792                                 if {$c1 eq {-}} {
793                                         set n [expr $n+1]
794                                         set patch "$patch$pre_context$ln"
795                                         set pre_context {}
796                                 } else {
797                                         set m [expr $m+1]
798                                         set patch "$patch$ln"
799                                 }
800                         } elseif {$c1 ne {-} && $c1 ne {+}} {
801                                 # context line
802                                 set ln [$ui_diff get $i_l $next_l]
803                                 set patch "$patch$pre_context$ln"
804                                 # Skip the "\ No newline at end of
805                                 # file". Depending on the locale setting
806                                 # we don't know what this line looks
807                                 # like exactly. The only thing we do
808                                 # know is that it starts with "\ "
809                                 if {![string match {\\ *} $ln]} {
810                                         set n [expr $n+1]
811                                         set m [expr $m+1]
812                                 }
813                                 set pre_context {}
814                         } elseif {$c1 eq $to_context} {
815                                 # turn change line into context line
816                                 set ln [$ui_diff get "$i_l + 1 chars" $next_l]
817                                 if {$c1 eq {-}} {
818                                         set pre_context "$pre_context $ln"
819                                 } else {
820                                         set patch "$patch $ln"
821                                 }
822                                 set n [expr $n+1]
823                                 set m [expr $m+1]
824                         } else {
825                                 # a change in the opposite direction of
826                                 # to_context which is outside the range of
827                                 # lines to apply.
828                                 set patch "$patch$pre_context"
829                                 set pre_context {}
830                         }
831                         set i_l $next_l
832                 }
833                 set patch "$patch$pre_context"
834                 set wholepatch "$wholepatch@@ -$hln,$n +$hln,$m @@\n$patch"
835                 set first_l [$ui_diff index "$next_l + 1 lines"]
836         }
837
838         if {[catch {
839                 set enc [get_path_encoding $current_diff_path]
840                 set p [eval git_write $apply_cmd]
841                 fconfigure $p -translation binary -encoding $enc
842                 puts -nonewline $p $current_diff_header
843                 puts -nonewline $p $wholepatch
844                 close $p} err]} {
845                 error_popup "$failed_msg\n\n$err"
846                 unlock_index
847                 return
848         }
849
850         if {$revert} {
851                 # Save a copy of this patch for undoing reverts.
852                 set last_revert $current_diff_header$wholepatch
853                 set last_revert_enc $enc
854         }
855
856         unlock_index
857 }
858
859 # Undo the last line/hunk reverted. When hunks and lines are reverted, a copy
860 # of the diff applied is saved. Re-apply that diff to undo the revert.
861 #
862 # Right now, we only use a single variable to hold the copy, and not a
863 # stack/deque for simplicity, so multiple undos are not possible. Maybe this
864 # can be added if the need for something like this is felt in the future.
865 proc undo_last_revert {} {
866         global last_revert current_diff_path current_diff_header
867         global last_revert_enc
868
869         if {$last_revert eq {}} return
870         if {![lock_index apply_hunk]} return
871
872         set apply_cmd {apply --whitespace=nowarn}
873         set failed_msg [mc "Failed to undo last revert."]
874
875         if {[catch {
876                 set enc $last_revert_enc
877                 set p [eval git_write $apply_cmd]
878                 fconfigure $p -translation binary -encoding $enc
879                 puts -nonewline $p $last_revert
880                 close $p} err]} {
881                 error_popup "$failed_msg\n\n$err"
882                 unlock_index
883                 return
884         }
885
886         set last_revert {}
887
888         unlock_index
889 }