Eskil

Check-in [393bb7a948]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Moved startup code to its own source file.
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 393bb7a948c3cc3385167224bc1ccfe410362935
User & Date: peter 2016-07-05 22:29:45.048
Context
2016-07-05
23:39
Support negative revisions with GIT. Added log view for GIT. check-in: abf4666387 user: peter tags: trunk
22:37
Experiment with worker thread. check-in: f6e6a1dde6 user: peter tags: thread
22:29
Moved startup code to its own source file. check-in: 393bb7a948 user: peter tags: trunk
2016-07-01
14:15
When displaying a patch, detect chunks marked with ##. check-in: f29a64fe0f user: peter tags: trunk
Changes
Unified Diff Ignore Whitespace Patch
Changes to Makefile.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
NAGELFAR    = nagelfar

all: setup

SRCFILES = src/eskil.tcl src/clip.tcl src/dirdiff.tcl src/help.tcl src/map.tcl \
	   src/print.tcl src/registry.tcl src/rev.tcl src/debug.tcl \
	   src/compare.tcl src/merge.tcl src/printobj.tcl src/plugin.tcl \
           src/vcsvfs.tcl

#----------------------------------------------------------------
# Build a dependency tree to other libs needed.
# This is made in a parallell VFS structure, mimicking Eskil's.
# Thus deps.vfs can also be created by downloading an Eskil kit,
# rename it to "deps" and unwrap it with sdx.
#----------------------------------------------------------------







|







31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
NAGELFAR    = nagelfar

all: setup

SRCFILES = src/eskil.tcl src/clip.tcl src/dirdiff.tcl src/help.tcl src/map.tcl \
	   src/print.tcl src/registry.tcl src/rev.tcl src/debug.tcl \
	   src/compare.tcl src/merge.tcl src/printobj.tcl src/plugin.tcl \
           src/vcsvfs.tcl src/startup.tcl

#----------------------------------------------------------------
# Build a dependency tree to other libs needed.
# This is made in a parallell VFS structure, mimicking Eskil's.
# Thus deps.vfs can also be created by downloading an Eskil kit,
# rename it to "deps" and unwrap it with sdx.
#----------------------------------------------------------------
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
	$(TCLKIT_LINUX) eskil.vfs/main.tcl

#----------------------------------------------------------------
# Coverage
#----------------------------------------------------------------

# Source files for code coverage
COVFILES = eskil.vfs/main.tcl eskil.vfs/src/rev.tcl eskil.vfs/src/eskil.tcl eskil.vfs/src/merge.tcl
IFILES   = $(COVFILES:.tcl=.tcl_i)
LOGFILES = $(COVFILES:.tcl=.tcl_log)
MFILES   = $(COVFILES:.tcl=.tcl_m)

# Instrument source file for code coverage
%.tcl_i: %.tcl eskil_h.syntax
	@$(NAGELFAR) -instrument eskil_h.syntax $<







|







158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
	$(TCLKIT_LINUX) eskil.vfs/main.tcl

#----------------------------------------------------------------
# Coverage
#----------------------------------------------------------------

# Source files for code coverage
COVFILES = eskil.vfs/main.tcl eskil.vfs/src/rev.tcl eskil.vfs/src/eskil.tcl eskil.vfs/src/merge.tcl eskil.vfs/src/startup.tcl
IFILES   = $(COVFILES:.tcl=.tcl_i)
LOGFILES = $(COVFILES:.tcl=.tcl_log)
MFILES   = $(COVFILES:.tcl=.tcl_m)

# Instrument source file for code coverage
%.tcl_i: %.tcl eskil_h.syntax
	@$(NAGELFAR) -instrument eskil_h.syntax $<
Changes to eskil.vfs/main.tcl.
1
2
3
package require starkit
starkit::startup
source $::starkit::topdir/src/eskil.tcl


|
1
2
3
package require starkit
starkit::startup
source $::starkit::topdir/src/startup.tcl
Changes to src/eskil.tcl.
1
2
3
4
5
6
7
8
#!/bin/sh
#---------------------------------------------------------- -*- tcl -*-
#
#  Eskil, a Graphical frontend to diff
#
#  Copyright (c) 1998-2015, Peter Spjuth  (peter.spjuth@gmail.com)
#
#  Usage
<








1
2
3
4
5
6
7

#---------------------------------------------------------- -*- tcl -*-
#
#  Eskil, a Graphical frontend to diff
#
#  Copyright (c) 1998-2015, Peter Spjuth  (peter.spjuth@gmail.com)
#
#  Usage
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#
#  You should have received a copy of the GNU General Public License
#  along with this program; see the file COPYING.  If not, write to
#  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
#  Boston, MA 02111-1307, USA.
#
#----------------------------------------------------------------------
# the next line restarts using tclsh \
exec tclsh "$0" "$@"

package require Tcl 8.5

# Stop Tk from meddling with the command line by copying it first.
set ::eskil(argv) $::argv
set ::eskil(argc) $::argc
set ::argv {}
set ::argc 0

set ::eskil(debug) 0
# Version string is loaded from version.txt
set ::eskil(diffver) "Version Unknown"
set ::eskil(thisScript) [file join [pwd] [info script]]

namespace import tcl::mathop::+
namespace import tcl::mathop::-
namespace import tcl::mathop::*
namespace import tcl::mathop::/

# Do initalisations for needed packages and globals.
# This is not run until needed to speed up command line error reporting.
proc Init {} {
    if {[info exists ::eskil(initHasRun)]} {
        return
    }
    set ::eskil(initHasRun) 1
    package require Tk 8.4
    catch {package require textSearch}
    package require wcb
    package require snit
    package require tablelist_tile

    if {[catch {package require psballoon}]} {
        # Add a dummy if it does not exist.
        proc addBalloon {args} {}
    } else {
        namespace import -force psballoon::addBalloon
    }

    set ::eskil(thisDir) [file dirname $::eskil(thisScript)]

    # Follow any link
    set tmplink $::eskil(thisScript)
    while {[file type $tmplink] eq "link"} {
        set tmplink [file readlink $tmplink]
        set tmplink [file normalize [file join $::eskil(thisDir) $tmplink]]
        set ::eskil(thisDir) [file dirname $tmplink]
    }

    if {[file exists $::eskil(thisDir)/../version.txt]} {
        set ch [open $::eskil(thisDir)/../version.txt]
        set ::eskil(diffver) [string trim [read $ch 100]]
        close $ch
    }

    # Get all other source files
    InitReSource

    # Diff functionality is in the DiffUtil package.
    package require DiffUtil
    # Help DiffUtil to find a diff executable, if needed
    catch {DiffUtil::LocateDiffExe $::eskil(thisScript)}

    # Create font for PDF
    if {$::Pref(printFont) eq ""} {
        set fontfile $::eskil(thisDir)/embedfont.ttf
    } else {
        set fontfile $::Pref(printFont)
    }
    # Allow fallback to PDF-builtin Courier
    if {$fontfile eq "Courier"} {
        set ::eskil(printFont) Courier
    } else {
        set ext [file extension $fontfile]
        if {$ext eq ".afm"} {
            pdf4tcl::loadBaseType1Font EskilBase $fontfile \
                    [file rootname $fontfile].pfb
        } else {
            pdf4tcl::loadBaseTrueTypeFont EskilBase $fontfile 1
        }

        pdf4tcl::createFont EskilBase EskilFont cp1251
        set ::eskil(printFont) EskilFont
    }

    # Figure out a place to store temporary files.
    locateTmp ::eskil(tmpdir)

    if {$::tcl_platform(platform) eq "windows"} {
        # Locate CVS if it is in c:/bin
        if {[auto_execok cvs] eq "" && [file exists "c:/bin/cvs.exe"]} {
            set ::env(PATH) "$::env(PATH);c:\\bin"
            auto_reset
        }
    }
    defaultGuiOptions
    if {0 && [bind all <Alt-KeyPress>] eq ""} {
        bind all <Alt-KeyPress> [bind Menubutton <Alt-KeyPress>]
        #after 500 "tk_messageBox -message Miffo"
    }
    wm withdraw .

    if {[catch {package require Ttk}]} {
        if {[catch {package require tile}]} {
            if {[info exists ::eskil_testsuite]} {
                return
            } else {
                puts "Themed Tk not found"
                exit
            }
        }
    }
    # Provide a ttk-friendly toplevel, fixing background and menubar
    if {[info commands ttk::toplevel] eq ""} {
        proc ttk::toplevel {w args} {
            tk::toplevel $w {*}$args
            place [ttk::frame $w.tilebg] -x 0 -y 0 -relwidth 1 -relheight 1
            return $w
        }
    }

    ::snit::widgetadaptor ttk::entryX {
        delegate method * to hull
        delegate option * to hull

        constructor {args} {
            installhull using ttk::entry
            $self configurelist $args
            # Make sure textvariable is initialised
            set varName [from args -textvariable ""]
            if {$varName ne ""} {
                upvar \#0 $varName var
                if {![info exists var]} {
                    set var ""
                }
            }
        }
        # Circumvent a bug in ttk::entry that "xview end" does not work.
        method xview {args} {
            if {[llength $args] == 1} {
                set ix [lindex $args 0]
                $hull xview [$hull index $ix]
            } else {
                $hull xview {*}$args
            }
        }
    }

    interp alias {} toplevel {} ttk::toplevel

    # Use demo images from Tablelist
    set dir $::eskil(thisDir)/../lib/tablelist/demos
    if {[catch {
        set ::img(clsd) [image create photo -file [file join $dir clsdFolder.gif]]
        set ::img(open) [image create photo -file [file join $dir openFolder.gif]]
        set ::img(file) [image create photo -file [file join $dir file.gif]]
    }]} then {
        set ::img(clsd) ""
        set ::img(open) ""
        set ::img(file) ""
    }
    # Local images
    set dir $::eskil(thisDir)/images
    set ::img(link) [image create photo -file [file join $dir link.gif]]
    set ::img(left) [image create photo -file [file join $dir arrow_left.gif]]
    set ::img(right) [image create photo -file [file join $dir arrow_right.gif]]
    set ::img(browse) [image create photo -file [file join $dir folderopen1.gif]]
    set ::img(up) [image create photo -file [file join $dir arrow_up.gif]]
    # Create a double up arrow
    set ih [image height $::img(up)]
    set iw [image width $::img(up)]
    set ::img(upup) [image create photo -height $ih -width [expr {2 * $iw}]]
    $::img(upup) copy $::img(up) -to 0 0 [expr {2 * $iw - 1}] [expr {$ih - 1}]

    EskilThemeInit
}

proc InitReSource {} {
    # Get all other source files
    source $::eskil(thisDir)/clip.tcl
    source $::eskil(thisDir)/compare.tcl
    source $::eskil(thisDir)/map.tcl
    source $::eskil(thisDir)/merge.tcl
    source $::eskil(thisDir)/registry.tcl
    source $::eskil(thisDir)/dirdiff.tcl
    source $::eskil(thisDir)/help.tcl
    source $::eskil(thisDir)/plugin.tcl
    source $::eskil(thisDir)/printobj.tcl
    source $::eskil(thisDir)/print.tcl
    source $::eskil(thisDir)/rev.tcl
    source $::eskil(thisDir)/debug.tcl

    # Only load vcsvfs if vfs is present
    if {![catch {package require vfs}]} {
        source $::eskil(thisDir)/vcsvfs.tcl
    }
}

# Debug function to be able to reread the source even when wrapped in a kit.
proc EskilRereadSource {} {
    set this $::eskil(thisScript)

    # FIXA: Better detection of starkit?
    # Maybe look at ::starkit::topdir ?

    #if {[info exists ::starkit::topdir]} {
    #    puts "Topdir: $::starkit::topdir"
    #}

    # Are we in a Starkit?
    if {[regexp {^(.*eskil)((?:\.[^/]+)?)(/src/.*)$} $this -> \
            pre ext post]} {
        if {$ext ne ".vfs"} {
            # If the unpacked vfs directory is available, read from that
            # instead.
            set src $pre.vfs$post
            if {[file readable $src]} {
                set this $src
            }
        }
    }
    puts "Resourcing $this"
    uplevel \#0 [list source $this]
    # Get all other source files
    InitReSource
}

# Initialize Ttk style settings
proc EskilThemeInit {} {
    # Import the 'default' theme border element.
    catch { ttk::style element create plain.border from default }
    catch { ttk::style element create plain.padding from default }
    catch { ttk::style element create plain.label from default }

    # Create a new style using the imported element.
    ttk::style layout My.Toolbutton {
        My.Toolbutton.plain.border -sticky nswe -children {
            My.Toolbutton.padding -sticky nswe -children {
                My.Toolbutton.label -sticky nswe
            }
        }
    }
    # Configure  our new style.
    ttk::style configure My.Toolbutton {*}[ttk::style configure Toolbutton] \
        -padding {1 1}
    ttk::style map My.Toolbutton {*}[ttk::style map Toolbutton] \
        -relief {disabled flat selected sunken pressed sunken active raised}
    # Re-do if the user changes theme.
    if {[lsearch -exact [bind . <<ThemeChanged>>] EskilThemeInit] == -1} {
        bind . <<ThemeChanged>> +EskilThemeInit
    }
}

# This function is called when a toplevel is closed.
# If it is the last remaining toplevel, the application quits.
# If top = "all" it means quit.
# If eskil is embedded, this should be used to close an eskil toplevel.
proc cleanupAndExit {top} {
    # A security thing to make sure we can exit.







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







20
21
22
23
24
25
26






























































































































































































































































27
28
29
30
31
32
33
#
#  You should have received a copy of the GNU General Public License
#  along with this program; see the file COPYING.  If not, write to
#  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
#  Boston, MA 02111-1307, USA.
#
#----------------------------------------------------------------------































































































































































































































































# This function is called when a toplevel is closed.
# If it is the last remaining toplevel, the application quits.
# If top = "all" it means quit.
# If eskil is embedded, this should be used to close an eskil toplevel.
proc cleanupAndExit {top} {
    # A security thing to make sure we can exit.
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043

    trace add variable ::eskil($top,prefregexa) write \
            [list EditPrefRegsubUpdate $top]
    trace add variable ::eskil($top,prefregexa2) write \
            [list EditPrefRegsubUpdate $top]
    EditPrefRegsubUpdate $top
}

proc defaultGuiOptions {} {
    # Turn off tearoff on all systems
    option add *Menu.tearOff 0
    if {[tk windowingsystem]=="x11"} {
        # Menubar looks out of place on linux. This adjusts the background
        # Which is enough to make it reasonable.
        set bg [ttk::style configure . -background]
        set sbg [ttk::style configure . -selectbackground]
        option add *Menubutton.background $bg
        option add *Menu.background $bg
        option add *Menu.activeBackground $sbg

        option add *Listbox.background $bg
        option add *Listbox.selectBackground $sbg
        option add *Text.background white
        option add *Text.selectBackground $sbg

        #option add *Scrollbar.takeFocus 0
        #option add *highlightThickness 0
    }
}

#####################################
# Startup stuff
#####################################

proc printUsage {} {
    puts {Usage: eskil [options] [files...]
  [options]  See below.
  [files...] Files to be compared

  If no files are given, the program is started anyway and you can select
  files from within. If only one file is given, the program looks for version
  control of the file, and if found, runs in version control mode.
  If directories are given, Eskil starts in directory diff.

  To list all options matching a prefix, run 'eskil --query prefix'.
  In tcsh use this line to get option completion:
  complete eskil 'C/-/`eskil --query -`/'

  Options:}

    # Dump option info
    foreach name [lsort -dictionary [dict keys $::eskil(opts,info)]] {
        set outName $name
        if {![dict exists $::eskil(opts,info) $name flag]} {
            puts "Internal Error: BOHOHOHO $name"
            break
        }
        if {![dict get $::eskil(opts,info) $name flag]} {
            append outName " <v>"
        }
        # Line up shorter ones
        if {[string length $outName] < 10} {
            set outName [format %-10s $outName]
        }
        set outName "$outName : "
        set indent [string length $outName]
        set len [expr {80 - $indent}]
        set d [dict get $::eskil(opts,info) $name shortdescr]
        if {$d eq "_"} continue
        while {$d ne ""} {
            if {[string length $d] <= $len} {
                set chunk $d
                set d ""
            } else {
                set ci $len
                while {[string index $d $ci] ne " " && $ci > 40} {
                    incr ci -1
                }
                set chunk [string range $d 0 $ci-1]
                set d [string trim [string range $d $ci end]]
            }
            puts "$outName$chunk"
            set outName [format %*s $indent ""]
        }
    }
}

#####################################
# Option/flag handling helpers
#####################################
# Validators
proc optValidatePdfColor {opt arg} {
    set fail 0
    if {![string is list $arg] || [llength $arg] != 3} {
        set fail 1
    } else {
        foreach val $arg {
            if {![string is double -strict $val] || $val < 0.0 || $val > 1.0} {
                set fail 1
            }
        }
    }
    if {$fail} {
        puts "Argument $opt must be a list of RBG values from 0.0 to 1.0"
        exit
    }
}
proc optValidatePositive {opt arg} {
    if {![string is double -strict $arg] || $arg <= 0} {
        puts "Argument $opt must be a positive number"
        exit
    }
}
proc optValidateNatural {opt arg} {
    if {![string is integer -strict $arg] || $arg < 0} {
        puts "Argument $opt must be a natural number"
        exit
    }
}
proc optValidatePaper {opt arg} {
    package require pdf4tcl
    if {[llength [pdf4tcl::getPaperSize $arg]] != 2} {
        puts "Argument $opt must be a valid paper size"
        puts "Valid paper sizes:"
        puts [join [lsort -dictionary [pdf4tcl::getPaperSizeList]] \n]
        exit
    }
}
proc optValidatePlugin {opt arg} {
    # We must start up completely to check a plugin
    Init
    set src [LocatePlugin $arg]
    if {$src eq ""} {
        puts "Bad plugin: $arg"
        printPlugins
        exit
    }
    # Look for declarations of command line options
    set ch [open $src r]
    while {[gets $ch line] >= 0} {
        # Only look until empty line
        if {[string trim $line] eq ""} break
        if {[regexp {^\#\# Option\s+(\S+)} $line -> name]} {
            addOpt $name
        }
        if {[regexp {^\#\# Flag\s+(\S+)} $line -> name]} {
            addFlags $name
        }
    }
    close $ch
}
# Option database setup
proc initOpts {} {
    set ::eskil(opts) {}
    set ::eskil(defoptinfo) {
        flag 0
        given 0
        multi 0
        type ""
        validator ""
        filter ""
        sideeffect ""
        shortdescr ""
        longdescr ""
    } 
}
# Add a command line flag that do not take a value
proc addFlags {args} {
    foreach name $args {
        dict set ::eskil(opts) $name 0
        dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
        dict set ::eskil(opts,info) $name flag  1
    }
}
# Document a flag
proc docFlag {name short {long {}}} {
    dict set ::eskil(opts,info) $name shortdescr $short
    dict set ::eskil(opts,info) $name longdescr $long
}

# Flag that affects Pref
proc addPrefFlag {name elem {value 1}} {
    dict set ::eskil(opts) $name 0
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
    dict set ::eskil(opts,info) $name flag  1
    dict set ::eskil(opts,info) $name type Pref
    dict set ::eskil(opts,info) $name "elem" $elem
    dict set ::eskil(opts,info) $name "value" $value
}
# Flag that affects local opts
proc addOptsFlag {name elem {value 1}} {
    dict set ::eskil(opts) $name 0
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
    dict set ::eskil(opts,info) $name flag  1
    dict set ::eskil(opts,info) $name type Opts
    dict set ::eskil(opts,info) $name "elem" $elem
    dict set ::eskil(opts,info) $name "value" $value
}
# Add a command line option that takes a value
proc addOpt {name {def ""}} {
    dict set ::eskil(opts) $name $def
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
}
# Add a command line option that takes a value and stores in Pref
proc addPrefOpt {name elem {validator ""}} {
    dict set ::eskil(opts) $name ""
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
    dict set ::eskil(opts,info) $name type Pref
    dict set ::eskil(opts,info) $name "elem" $elem
    dict set ::eskil(opts,info) $name "validator" $validator
}
# Add a vaildator command to an Opt
proc addValidator {name cmd} {
    dict set ::eskil(opts,info) $name validator $cmd
}
# Add a filter command prefix to an Opt
proc addFilter {name cmd} {
    dict set ::eskil(opts,info) $name filter $cmd
}
# Add a sideeffect to an Opt
##nagelfar syntax addSideEffect x c
proc addSideEffect {name script} {
    dict set ::eskil(opts,info) $name sideeffect $script
}
# Add a command line option that takes a value and stores in local opts
proc addOptsOpt {name elem {validator ""}} {
    dict set ::eskil(opts) $name ""
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
    dict set ::eskil(opts,info) $name type Opts
    dict set ::eskil(opts,info) $name "elem" $elem
    dict set ::eskil(opts,info) $name "validator" $validator
}
# Add a command line option that takes multiple values
proc addMultOpt {name} {
    dict set ::eskil(opts) $name {}
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
    dict set ::eskil(opts,info) $name multi 1
}
# List all known options
proc allOpts {{pat *}} {
    return [dict keys $::eskil(opts) $pat]
}
proc optIsFlag {arg} {
    return [dict get $::eskil(opts,info) $arg flag]
}
proc optIsGiven {arg valName} {
    upvar 1 $valName val
    set val [dict get $::eskil(opts) $arg]
    return [dict get $::eskil(opts,info) $arg given]
}
proc optSet {arg val} {
    if {[dict get $::eskil(opts,info) $arg multi]} {
        dict lappend ::eskil(opts) $arg $val
    } else {
        dict set ::eskil(opts) $arg $val
    }
    # If it is a flag, the value can come from the settings
    if {[dict exists $::eskil(opts,info) $arg value]} {
        set val [dict get $::eskil(opts,info) $arg value]
    }
    # Any validator?
    set cmd [dict get $::eskil(opts,info) $arg validator]
    if {$cmd ne ""} {
        # The validator will exit if it fails
        $cmd $arg $val
    }
    # Any filter?
    set cmd [dict get $::eskil(opts,info) $arg filter]
    if {$cmd ne ""} {
        set val [{*}$cmd $val]
    }
    # Any side effect?
    set cmd [dict get $::eskil(opts,info) $arg sideeffect]
    if {$cmd ne ""} {
        uplevel 1 $cmd
    }

    set type [dict get $::eskil(opts,info) $arg type]
    switch $type {
        Pref {
            set ::Pref([dict get $::eskil(opts,info) $arg elem]) $val
        }
        Opts {
            upvar 1 opts _xx
            set _xx([dict get $::eskil(opts,info) $arg elem]) $val
        }
    }
    dict set ::eskil(opts,info) $arg given 1
}
proc optGet {arg} {
    return [dict get $::eskil(opts) $arg]
}

# Helper to add a file argument to list of files
proc cmdLineAddFile {filesName arg} {
    upvar 1 $filesName files
    set apa [file normalize [file join [pwd] $arg]]
    if {![file exists $apa]} {
        puts "Bad argument: $arg"
        exit
    } else {
        lappend files $apa
    }
}

# Go through all command line arguments and start the appropriate
# diff window.
# Returns the created toplevel.
# This can be used as an entry point if embedding eskil.
# In that case fill in ::eskil(argv) and ::eskil(argc) before calling.
proc parseCommandLine {} {
    global dirdiff

    set ::eskil(autoclose) 0
    set ::eskil(ignorenewline) 0
    set ::eskil(defaultopts) {}

    if {$::eskil(argc) == 0} {
        Init
        return [makeDiffWin]
    }

    # Set up all options info
    initOpts
    addFlags --help -help
    
    addPrefFlag -w          ignore -w
    addPrefFlag -b          ignore -b 
    addPrefFlag -noignore   ignore " "
    docFlag     -w          "Ignore all spaces"
    docFlag     -b          "Ignore space changes (default)"
    docFlag     -noignore   "Don't ignore any whitespace"
    addPrefFlag -noparse    parse 0
    addPrefFlag -line       parse 1
    addPrefFlag -smallblock parse 2
    addPrefFlag -block      parse 3
    docFlag -noparse    "No block analysis"
    docFlag -line       "Line based block analysis"
    docFlag -smallblock "Do block analysis on small blocks (default)"
    docFlag -block      "Full block analysis. This can be slow if there are large change blocks"

    addPrefFlag -char       lineparsewords 0
    addPrefFlag -word       lineparsewords 1
    docFlag     -char       "Character based change view (default)"
    docFlag     -word       "Word based change view"
    addPrefFlag -i          nocase
    addPrefFlag -nocase     nocase 
    docFlag     -i          "Ignore case changes"
    docFlag     -nocase     "Ignore case changes"
    addPrefFlag -nodigit    nodigit
    docFlag     -nodigit    "Ignore digit changes"
    addPrefFlag -nokeyword  dir,ignorekey
    docFlag     -nokeyword  "In directory diff, ignore \$ Keywords: \$"
    addPrefFlag -noempty    noempty
    docFlag     -noempty    "Ignore empty lines initially for matching"
    addPrefFlag -fine       finegrainchunks
    docFlag     -fine       "Use fine grained chunks. Useful for merging"
    addOptsFlag -table      view  table
    docFlag     -table      "Run in table mode"
    addOptsFlag -conflict mode conflict
    docFlag -conflict "Treat file as a merge conflict file and enter merge mode"
    # Conflict implies foreach
    addSideEffect -conflict {
        optSet -foreach 1
    }
    addFlags -dir -clip -patch -review -
    docFlag -dir    "Start in directory diff mode. Ignores other args"
    docFlag -clip   "Start in clip diff mode. Ignores other args"
    docFlag -patch  "View patch file"
    docFlag -       "Read patch file from standard input, to allow pipes"
    docFlag -review "View revision control tree as a patch."
    addFlags -browse -nodiff
    docFlag -browse "Automatically bring up file dialog after starting"
    docFlag -nodiff "Do not run diff after startup"
    addFlags -server -cvs -svn -debug
    docFlag -server "Set up Eskil to be controllable from the outside"
    docFlag -cvs    "Detect CVS first, if multiple version systems are used"
    docFlag -svn    "Detect SVN first, if multiple version systems are used"
    docFlag -debug  "Start in debug mode"
    addFlags -foreach -close
    docFlag -foreach "Open one diff window per file listed"
    docFlag -close   "Close windows with no changes"
    addFlags -nonewline -nonewline+ -nocdiff
    docFlag -nonewline  "Try to ignore newline changes"
    docFlag -nonewline+ "Try to ignore newline changes, and don't display"
    docFlag -nocdiff    "Disable C version of DiffUtil. For debug"
    addFlags -pluginlist -pluginallow
    docFlag -pluginlist  "List known plugins"
    docFlag -pluginallow "Allow full access privilege for a plugin"
    # Options that take values
    addOpt   -plugin
    docFlag  -plugin "Preprocess files using plugin"
    addValidator -plugin optValidatePlugin
    addOpt   -plugininfo
    docFlag  -plugininfo "Pass info to plugin (plugin specific)"
    addOpt   -plugindump
    docFlag  -plugindump "Dump plugin source to stdout"
    # These options affect Pref
    addPrefOpt -pivot             pivot             optValidatePositive
    docFlag    -pivot "Pivot setting for diff algorithm (100)"
    addPrefOpt -context           context           optValidateNatural
    docFlag    -context "Show only differences, with <n> lines of context"
    addPrefOpt -printHeaderSize   printHeaderSize   optValidatePositive
    addPrefOpt -printCharsPerLine printCharsPerLine optValidatePositive
    addPrefOpt -printPaper        printPaper        optValidatePaper
    addPrefOpt -printColorChange  printColorChange  optValidatePdfColor
    addPrefOpt -printColorOld     printColorOld     optValidatePdfColor  
    addPrefOpt -printColorNew     printColorNew     optValidatePdfColor
    addPrefOpt -printFont         printFont
    docFlag -printHeaderSize   "Font size for page header (10)"
    docFlag -printCharsPerLine "Adapt font size for this line length and wrap (80)"
    docFlag -printPaper       "Select paper size (a4)"
    docFlag -printColorChange "Color for change (1.0 0.7 0.7)"
    docFlag -printColorOld    "Color for old text (0.7 1.0 0.7)"
    docFlag -printColorNew    "Color for new text (0.8 0.8 1.0)"
    docFlag -printFont "Select font to use in PDF, afm or ttf. If <fontfile> is given as \"Courier\", PDF built in font is used"
    addMultOpt -prefix
    docFlag    -prefix "Care mainly about words starting with \"str\""
    addMultOpt -preprocess
    addMultOpt -preprocessleft
    addMultOpt -preprocessright
    docFlag    -preprocess  "TBW <pair>"
    docFlag    -preprocessleft  "TBW <pair>"
    docFlag    -preprocessright "TBW <pair>"
    # These affect opts
    addOptsOpt -limit    limitlines
    docFlag    -limit "Do not process more than <lines> lines"
    addOptsOpt -maxwidth maxwidth
    docFlag    -maxwidth "Limit column width in table mode"
    addOptsOpt -o mergeFile 
    docFlag    -o "Specify merge result output file"
    addFilter  -o [list file join [pwd]]
    addOptsOpt -a ancestorFile
    docFlag    -a "Give ancestor file for three way merge"
    addFilter  -a [list file join [pwd]]
    # Default is no ignore on three-way merge
    addSideEffect -a { set ::Pref(ignore) " " }
    addOptsOpt -sep separator
    docFlag -sep "See char <c> as separator between columns in files"
    # Handle if separator is given e.g. as '\t'
    addFilter  -sep [list subst -nocommands -novariables]
    addOptsOpt -print    printFile
    docFlag -print           "Generate PDF and exit."
    addOptsOpt -printpdf printFile ;# Old option
    docFlag -printpdf        "_"
    addSideEffect -print    { set opts(printFileCmd) 1 }
    addSideEffect -printpdf { set opts(printFileCmd) 1 }
    addMultOpt -r
    docFlag -r "Version info for version control mode"

    # If the first option is "--query", use it to ask about options.
    if {$::eskil(argc) == 2 && [lindex $::eskil(argv) 0] == "--query"} {
        set arg [lindex $::eskil(argv) 1]
        set allOpts [allOpts]
        if {[lsearch -exact $allOpts $arg] < 0} {
            set match [lsearch -glob -all -inline $allOpts $arg*]
        } else {
            set match [list $arg]
        }
        puts [lsort -dictionary $match]
        exit
    }

    # Go through and fill in options
    set files {}
    for {set i 0} {$i < [llength $::eskil(argv)]} {incr i} {
        set arg [lindex $::eskil(argv) $i]
        # Non-dash means not an option
        if {[string index $arg 0] ne "-"} {
            cmdLineAddFile files $arg
            continue
        }
        if {$arg eq "-"} {
            # Allow "-" for stdin patch processing
            lappend files "-"
            continue
        }
        # Take care of the special case of RCS style -r<rev>
        if {$arg ne "-review" && [string range $arg 0 1] eq "-r" && \
                    [string length $arg] > 2} {
            optSet -r [string range $arg 2 end]
            continue
        }
        # Handle unknowns
        if {![dict exists $::eskil(opts) $arg]} {
            # Try to see if it is an unique abbreviation of an option.
            set match [allOpts $arg*]
            if {[llength $match] == 1} {
                set arg [lindex $match 0]
            } else {
                # If not, try to put it among files
                cmdLineAddFile files $arg
                continue
            }
        }
        # Flags
        if {[optIsFlag $arg]} {
            set val 1
        } else {
            # Options with values
            incr i
            set val [lindex $::eskil(argv) $i]
        }
        optSet $arg $val
    }

    # Any help flag given just prints and exits
    if {[optIsGiven -help arg] || [optIsGiven --help arg]} {
        printUsage
        exit
    }

    # All options have been parsed, extract them to where they need to go

    # Straight to locals
    set plugin      [optGet -plugin]
    set plugininfo  [optGet -plugininfo]
    set plugindump  [optGet -plugindump]
    set pluginlist  [optGet -pluginlist]
    set pluginallow [optGet -pluginallow]
    set noautodiff  [optGet -nodiff]
    set nocdiff     [optGet -nocdiff]
    set dodir       [optGet -dir]
    set doclip      [optGet -clip]
    set dopatch     [optGet -patch]
    set doreview    [optGet -review]
    set autobrowse  [optGet -browse]
    set foreach     [optGet -foreach]
    set preferedRev "GIT"
    if {[optGet -svn]} {
        set preferedRev "SVN"
    } elseif {[optGet -cvs]} {
        set preferedRev "CVS"
    }

    # These directly correspond to ::eskil settings
    set apa {
        -nonewline  ignorenewline 1
        -nonewline+ ignorenewline 2
        -close      autoclose 1
        -debug      debug 1
    }
    foreach {opt elem val} $apa {
        if {[optIsGiven $opt arg]} {
            set ::eskil($elem) $val
        }
    }

    # Options that need individual checking/processing
    if {[optIsGiven -prefix arg]} {
        foreach apa $arg {
            set RE [string map [list % $apa] {^.*?\m(%\w+).*$}]
            if {$::Pref(nocase)} {
                set RE "(?i)$RE"
            }
            lappend ::Pref(preprocess) $RE {\1} ""
        }
    }
    if {[optIsGiven -preprocess arg]} {
        # FIXA: better validity check
        foreach apa $arg {
            foreach {RE sub} $apa {
                lappend ::Pref(preprocess) $RE $sub ""
            }
        }
    }
    if {[optIsGiven -preprocessleft arg]} {
        # FIXA: better validity check
        foreach apa $arg {
            foreach {RE sub} $apa {
                lappend ::Pref(preprocess) $RE $sub left
            }
        }
    }
    if {[optIsGiven -preprocessright arg]} {
        # FIXA: better validity check
        foreach apa $arg {
            foreach {RE sub} $apa {
                lappend ::Pref(preprocess) $RE $sub right
            }
        }
    }
    # Handle list of revisions
    if {[optIsGiven -r arg]} {
        set revNo 1
        foreach rev $arg {
            set opts(doptrev$revNo) $rev
            incr revNo
        }
    }
    if {[optGet -server]} {
        if {$::tcl_platform(platform) eq "windows"} {
            catch {
                package require dde
                dde servername Eskil
            }
        } else {
            package require Tk
            tk appname Eskil
        }
    }

    # Option handling done. Lets get started.

    Init

    if {$nocdiff} {
        DisableDiffUtilC
    }

    if {$pluginlist} {
        printPlugins
        exit
    }
    if {$plugindump ne ""} {
        printPlugin $plugindump
        exit
    }
    if {$plugin ne ""} {
        set pinterp [createPluginInterp $plugin $plugininfo $pluginallow pinfo]
        if {$pinterp eq ""} {
            # This should not happen since the validator should handle it
            puts "Bad plugin: $plugin"
            printPlugins
            exit
        }
        set opts(plugin) $pinterp
        set opts(pluginname) $plugin
        set opts(pluginallow) $pluginallow
        set opts(plugininfo) $plugininfo
        set opts(pluginpinfo) $pinfo
    }

    # Store the command line given opts
    set ::eskil(defaultopts) [array get opts]

    # Do we start in clip diff mode?
    if {$doclip} {
        return [makeClipDiffWin]
    }

    # Figure out if we start in a diff or dirdiff window.
    set len [llength $files]

    if {$len == 0 && $dodir} {
        set dirdiff(leftDir) ""
        set dirdiff(rightDir) ""
        return [makeDirDiffWin]
    }
    if {$len == 1} {
        set fullname [lindex $files 0]
        if {[FileIsDirectory $fullname 1]} {
            set dirdiff(leftDir) $fullname
            set dirdiff(rightDir) $dirdiff(leftDir)
            return [makeDirDiffWin]
        }
    } elseif {$len >= 2} {
        set fullname1 [lindex $files 0]
        set fullname2 [lindex $files 1]
        if {[FileIsDirectory $fullname1 1] && [FileIsDirectory $fullname2 1]} {
            set dirdiff(leftDir) $fullname1
            set dirdiff(rightDir) $fullname2
            return [makeDirDiffWin]
        }
    }

    # Ok, we have a normal diff
    set top [makeDiffWin]
    update

    # It is preferable to see the end if the rev string is too long
    $::widgets($top,rev1) xview end
    $::widgets($top,rev2) xview end

    if {$doreview} {
        set rev [detectRevSystem "" $preferedRev]
        set ::eskil($top,modetype) $rev
        set ::eskil($top,mode) "patch"
        set ::eskil($top,patchFile) ""
        set ::eskil($top,patchData) ""
        set ::eskil($top,reviewFiles) $files
        set ::Pref(toolbar) 1
        after idle [list doDiff $top]
        return $top
    }
    if {$len == 1 || $foreach} {
        set ReturnAfterLoop 0
        set first 1
        foreach file $files {
            if {$first} {
                set first 0
            } else {
                # Create new window for other files
                set top [makeDiffWin $top]
                update
                # It is preferable to see the end if the rev string is too long
                $::widgets($top,rev1) xview end
                $::widgets($top,rev2) xview end
            }
            set fullname $file
            set fulldir [file dirname $fullname]
            if {$::eskil($top,mode) eq "conflict"} {
                startConflictDiff $top $fullname
                after idle [list doDiff $top]
                set ReturnAfterLoop 1
                continue
            }
            if {!$autobrowse && !$dopatch} {
                # Check for revision control
                set rev [detectRevSystem $fullname $preferedRev]
                if {$rev ne ""} {
                    startRevMode $top $rev $fullname
                    if {$noautodiff} {
                        enableRedo $top
                    } else {
                        after idle [list doDiff $top]
                    }
                    set ReturnAfterLoop 1
                    continue
                }
            }
            # No revision control. Is it a patch file?
            set ::eskil($top,leftDir) $fulldir
            set ::eskil($top,leftFile) $fullname
            set ::eskil($top,leftLabel) $fullname
            set ::eskil($top,leftOK) 1
            if {$dopatch                                 || \
                    [regexp {\.(diff|patch)$} $fullname] || \
                    $fullname eq "-"} {
                set ::eskil($top,mode) "patch"
                set ::eskil($top,patchFile) $fullname
                set ::eskil($top,patchData) ""
                set autobrowse 0
                if {$noautodiff} {
                    enableRedo $top
                } else {
                    after idle [list doDiff $top]
                }
                set ReturnAfterLoop 1
                continue
            }
        }
        if {$ReturnAfterLoop} {return $top}
    } elseif {$len >= 2} {
        set fullname [file join [pwd] [lindex $files 0]]
        set fulldir [file dirname $fullname]
        set ::eskil($top,leftDir) $fulldir
        set ::eskil($top,leftFile) $fullname
        set ::eskil($top,leftLabel) $fullname
        set ::eskil($top,leftOK) 1
        set fullname [file join [pwd] [lindex $files 1]]
        set fulldir [file dirname $fullname]
        set ::eskil($top,rightDir) $fulldir
        set ::eskil($top,rightFile) $fullname
        set ::eskil($top,rightLabel) $fullname
        set ::eskil($top,rightOK) 1
        if {$noautodiff} {
            enableRedo $top
        } else {
            after idle [list doDiff $top]
        }
    }
    if {$autobrowse && (!$::eskil($top,leftOK) || !$::eskil($top,rightOK))} {
        if {!$::eskil($top,leftOK) && !$::eskil($top,rightOK)} {
            openBoth $top 0
        } elseif {!$::eskil($top,leftOK)} {
            openLeft $top
        } elseif {!$::eskil($top,rightOK)} {
            openRight $top
        }
        # If we cancel the second file and detect CVS, ask about it.
        # TBD: Extend this to all VCS:s?
        if {$::eskil($top,leftOK) && !$::eskil($top,rightOK) && \
                [llength [glob -nocomplain [file join $fulldir CVS]]]} {

            if {[tk_messageBox -title Diff -icon question \
                    -message "Do CVS diff?" -type yesno] eq "yes"} {
                set fullname $::eskil($top,leftFile)
                set ::eskil($top,leftOK) 0
                startRevMode $top "CVS" $fullname
                after idle [list doDiff $top]
            }
        }
    }
    return $top
}

# Save options to file ~/.eskilrc
proc saveOptions {top} {
    # Is this a diff win or some other win?
    if {[info exists ::widgets($top,wDiff1)]} {
        # Check if the window size has changed
        set w $::widgets($top,wDiff1)
        if {[winfo reqwidth $w] != [winfo width $w] || \
                    [winfo reqheight $w] != [winfo height $w]} {
            set dx [expr {[winfo width $w] - [winfo reqwidth $w]}]
            set dy [expr {[winfo height $w] - [winfo reqheight $w]}]
            set cx [font measure myfont 0]
            set cy [font metrics myfont -linespace]
            set neww [expr {[$w cget -width]  + $dx / $cx}]
            set newh [expr {[$w cget -height] + $dy / $cy}]
            if {$neww != $::Pref(linewidth) || $newh != $::Pref(lines)} {
                set msg "Should I save the current window\
                    size with the preferences?\nCurrent: $neww x $newh  Old:\
                    $::Pref(linewidth) x $::Pref(lines)"
                set apa [tk_messageBox -title "Save Preferences" \
                                 -icon question -type yesno -message $msg]
                if {$apa == "yes"} {
                    set ::Pref(linewidth) $neww
                    set ::Pref(lines) $newh
                }
            }
        }
    }

    set rcfile "~/.eskilrc"
    if {[catch {set ch [open $rcfile "w"]} err]} {
        tk_messageBox -icon error -title "File error" -message \
                "Error when trying to save preferences:\n$err"
        return
    }

    foreach i [array names ::Pref] {
        # Skip unchanged options.
        if {[info exists ::DefaultPref($i)]} {
            if {$::DefaultPref($i) eq $::Pref($i)} {
                continue
            }
            puts $ch "# $i default : $::DefaultPref($i)"
        }
        puts $ch [list set "::Pref($i)" $::Pref($i)]
    }
    close $ch

    tk_messageBox -icon info -title "Saved" -message \
            "Preferences saved to:\n[file nativename $rcfile]"
}

proc getOptions {} {
    if {$::tcl_platform(os) eq "Darwin"} {
        set ::DefaultPref(fontsize) 10
    } else {
        set ::DefaultPref(fontsize) 8
    }
    # Maybe change to TkFixedFont in 8.5 ?
    set ::DefaultPref(fontfamily) Courier
    set ::DefaultPref(ignore) "-b"
    set ::DefaultPref(nocase) 0
    set ::DefaultPref(noempty) 0
    set ::DefaultPref(pivot) 100
    set ::DefaultPref(nodigit) 0
    set ::DefaultPref(parse) 2
    set ::DefaultPref(lineparsewords) 0
    set ::DefaultPref(colorequal) ""
    set ::DefaultPref(colorchange) red
    set ::DefaultPref(colornew1) darkgreen
    set ::DefaultPref(colornew2) blue
    set ::DefaultPref(bgequal) ""
    set ::DefaultPref(bgchange) \#ffe0e0
    set ::DefaultPref(bgnew1) \#a0ffa0
    set ::DefaultPref(bgnew2) \#e0e0ff
    set ::DefaultPref(context) -1
    set ::DefaultPref(finegrainchunks) 0
    set ::DefaultPref(marklast) 1
    set ::DefaultPref(linewidth) 80
    set ::DefaultPref(lines) 60
    set ::DefaultPref(editor) ""
    set ::DefaultPref(preprocess) {}
    set ::DefaultPref(toolbar) 0
    set ::DefaultPref(wideMap) 0 ;# Not settable in GUI yet

    # Print options
    set ::DefaultPref(printHeaderSize) 10
    set ::DefaultPref(printCharsPerLine) 80
    set ::DefaultPref(printPaper) a4
    set ::DefaultPref(printColorChange) "1.0 0.7 0.7"
    set ::DefaultPref(printColorNew1)   "0.7 1.0 0.7"
    set ::DefaultPref(printColorNew2)   "0.8 0.8 1.0"
    set ::DefaultPref(printFont) ""

    # Directory diff options
    set ::DefaultPref(dir,comparelevel) 1
    set ::DefaultPref(dir,ignorekey) 0
    set ::DefaultPref(dir,incfiles) ""
    set ::DefaultPref(dir,exfiles) "*.o"
    set ::DefaultPref(dir,incdirs) ""
    set ::DefaultPref(dir,exdirs) "RCS CVS .git .svn .hg"
    set ::DefaultPref(dir,onlyrev) 0
    set ::DefaultPref(dir,nice) 1

    # Start with default preferences, before loading setup file
    array set ::Pref [array get ::DefaultPref]

    # Backward compatibilty options
    set ::Pref(onlydiffs) -1
    set ::Pref(regsub) {}

    set ::eskil(filter) ""

    if {![info exists ::eskil_testsuite] && [file exists "~/.eskilrc"]} {
        safeLoad "~/.eskilrc" ::Pref
    }

    if {$::Pref(editor) ne ""} {
        set ::util(editor) $::Pref(editor)
    }

    # If the user's file has this old option, translate it to the new
    if {$::Pref(onlydiffs) == 0} {
        set ::Pref(context) -1
    }
    unset ::Pref(onlydiffs)
    if {$::Pref(regsub) ne ""} {
        foreach {a b} $::Pref(regsub) {
            lappend ::Pref(preprocess) $a $b ""
        }
    }
    unset ::Pref(regsub)

    # Set up reactions to some Pref settings
    if {![info exists ::widgets(toolbars)]} {
        set ::widgets(toolbars) {}
    }
    trace add variable ::Pref(toolbar) write TraceToolbar
}

proc TraceToolbar {args} {
    # FIXA: Handle destroyed windows ?
    foreach __ $::widgets(toolbars) {
        if {$::Pref(toolbar)} {
            grid configure $__
        } else {
            grid remove $__
        }
    }
}

# Global code is only run the first time to be able to reread source
if {![info exists ::eskil(gurkmeja)]} {
    set ::eskil(gurkmeja) 1

    package require pstools
    namespace import -force pstools::*
    getOptions
    if {![info exists ::eskil_testsuite]} {
        parseCommandLine
    }
}







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
3841
3842
3843
3844
3845
3846
3847














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































    trace add variable ::eskil($top,prefregexa) write \
            [list EditPrefRegsubUpdate $top]
    trace add variable ::eskil($top,prefregexa2) write \
            [list EditPrefRegsubUpdate $top]
    EditPrefRegsubUpdate $top
}













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Added src/startup.tcl.














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
#!/bin/sh
#---------------------------------------------------------- -*- tcl -*-
#
#  Eskil, a Graphical frontend to diff
#
#  Copyright (c) 1998-2015, Peter Spjuth  (peter.spjuth@gmail.com)
#
#  Usage
#             Do 'eskil' for interactive mode
#             Do 'eskil --help' for command line usage
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; see the file COPYING.  If not, write to
#  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
#  Boston, MA 02111-1307, USA.
#
#----------------------------------------------------------------------
# the next line restarts using tclsh \
exec tclsh "$0" "$@"

package require Tcl 8.5

# Stop Tk from meddling with the command line by copying it first.
set ::eskil(argv) $::argv
set ::eskil(argc) $::argc
set ::argv {}
set ::argc 0

set ::eskil(debug) 0
# Version string is loaded from version.txt
set ::eskil(diffver) "Version Unknown"
set ::eskil(thisScript) [file join [pwd] [info script]]

namespace import tcl::mathop::+
namespace import tcl::mathop::-
namespace import tcl::mathop::*
namespace import tcl::mathop::/

# Do initalisations for needed packages and globals.
# This is not run until needed to speed up command line error reporting.
proc Init {} {
    if {[info exists ::eskil(initHasRun)]} {
        return
    }
    set ::eskil(initHasRun) 1
    package require Tk 8.4
    catch {package require textSearch}
    package require wcb
    package require snit
    package require tablelist_tile

    if {[catch {package require psballoon}]} {
        # Add a dummy if it does not exist.
        proc addBalloon {args} {}
    } else {
        namespace import -force psballoon::addBalloon
    }

    set ::eskil(thisDir) [file dirname $::eskil(thisScript)]

    # Follow any link
    set tmplink $::eskil(thisScript)
    while {[file type $tmplink] eq "link"} {
        set tmplink [file readlink $tmplink]
        set tmplink [file normalize [file join $::eskil(thisDir) $tmplink]]
        set ::eskil(thisDir) [file dirname $tmplink]
    }

    if {[file exists $::eskil(thisDir)/../version.txt]} {
        set ch [open $::eskil(thisDir)/../version.txt]
        set ::eskil(diffver) [string trim [read $ch 100]]
        close $ch
    }

    # Get all other source files
    InitReSource

    # Diff functionality is in the DiffUtil package.
    package require DiffUtil
    # Help DiffUtil to find a diff executable, if needed
    catch {DiffUtil::LocateDiffExe $::eskil(thisScript)}

    # Create font for PDF
    if {$::Pref(printFont) eq ""} {
        set fontfile $::eskil(thisDir)/embedfont.ttf
    } else {
        set fontfile $::Pref(printFont)
    }
    # Allow fallback to PDF-builtin Courier
    if {$fontfile eq "Courier"} {
        set ::eskil(printFont) Courier
    } else {
        set ext [file extension $fontfile]
        if {$ext eq ".afm"} {
            pdf4tcl::loadBaseType1Font EskilBase $fontfile \
                    [file rootname $fontfile].pfb
        } else {
            pdf4tcl::loadBaseTrueTypeFont EskilBase $fontfile 1
        }

        pdf4tcl::createFont EskilBase EskilFont cp1251
        set ::eskil(printFont) EskilFont
    }

    # Figure out a place to store temporary files.
    locateTmp ::eskil(tmpdir)

    if {$::tcl_platform(platform) eq "windows"} {
        # Locate CVS if it is in c:/bin
        if {[auto_execok cvs] eq "" && [file exists "c:/bin/cvs.exe"]} {
            set ::env(PATH) "$::env(PATH);c:\\bin"
            auto_reset
        }
    }
    defaultGuiOptions
    if {0 && [bind all <Alt-KeyPress>] eq ""} {
        bind all <Alt-KeyPress> [bind Menubutton <Alt-KeyPress>]
        #after 500 "tk_messageBox -message Miffo"
    }
    wm withdraw .

    if {[catch {package require Ttk}]} {
        if {[catch {package require tile}]} {
            if {[info exists ::eskil_testsuite]} {
                return
            } else {
                puts "Themed Tk not found"
                exit
            }
        }
    }
    # Provide a ttk-friendly toplevel, fixing background and menubar
    if {[info commands ttk::toplevel] eq ""} {
        proc ttk::toplevel {w args} {
            tk::toplevel $w {*}$args
            place [ttk::frame $w.tilebg] -x 0 -y 0 -relwidth 1 -relheight 1
            return $w
        }
    }

    ::snit::widgetadaptor ttk::entryX {
        delegate method * to hull
        delegate option * to hull

        constructor {args} {
            installhull using ttk::entry
            $self configurelist $args
            # Make sure textvariable is initialised
            set varName [from args -textvariable ""]
            if {$varName ne ""} {
                upvar \#0 $varName var
                if {![info exists var]} {
                    set var ""
                }
            }
        }
        # Circumvent a bug in ttk::entry that "xview end" does not work.
        method xview {args} {
            if {[llength $args] == 1} {
                set ix [lindex $args 0]
                $hull xview [$hull index $ix]
            } else {
                $hull xview {*}$args
            }
        }
    }

    interp alias {} toplevel {} ttk::toplevel

    # Use demo images from Tablelist
    set dir $::eskil(thisDir)/../lib/tablelist/demos
    if {[catch {
        set ::img(clsd) [image create photo -file [file join $dir clsdFolder.gif]]
        set ::img(open) [image create photo -file [file join $dir openFolder.gif]]
        set ::img(file) [image create photo -file [file join $dir file.gif]]
    }]} then {
        set ::img(clsd) ""
        set ::img(open) ""
        set ::img(file) ""
    }
    # Local images
    set dir $::eskil(thisDir)/images
    set ::img(link) [image create photo -file [file join $dir link.gif]]
    set ::img(left) [image create photo -file [file join $dir arrow_left.gif]]
    set ::img(right) [image create photo -file [file join $dir arrow_right.gif]]
    set ::img(browse) [image create photo -file [file join $dir folderopen1.gif]]
    set ::img(up) [image create photo -file [file join $dir arrow_up.gif]]
    # Create a double up arrow
    set ih [image height $::img(up)]
    set iw [image width $::img(up)]
    set ::img(upup) [image create photo -height $ih -width [expr {2 * $iw}]]
    $::img(upup) copy $::img(up) -to 0 0 [expr {2 * $iw - 1}] [expr {$ih - 1}]

    EskilThemeInit
}

proc InitReSource {} {
    # Get all other source files
    source $::eskil(thisDir)/eskil.tcl
    source $::eskil(thisDir)/clip.tcl
    source $::eskil(thisDir)/compare.tcl
    source $::eskil(thisDir)/map.tcl
    source $::eskil(thisDir)/merge.tcl
    source $::eskil(thisDir)/registry.tcl
    source $::eskil(thisDir)/dirdiff.tcl
    source $::eskil(thisDir)/help.tcl
    source $::eskil(thisDir)/plugin.tcl
    source $::eskil(thisDir)/printobj.tcl
    source $::eskil(thisDir)/print.tcl
    source $::eskil(thisDir)/rev.tcl
    source $::eskil(thisDir)/debug.tcl

    # Only load vcsvfs if vfs is present
    if {![catch {package require vfs}]} {
        source $::eskil(thisDir)/vcsvfs.tcl
    }
}

# Debug function to be able to reread the source even when wrapped in a kit.
proc EskilRereadSource {} {
    set this $::eskil(thisScript)

    # FIXA: Better detection of starkit?
    # Maybe look at ::starkit::topdir ?

    #if {[info exists ::starkit::topdir]} {
    #    puts "Topdir: $::starkit::topdir"
    #}

    # Are we in a Starkit?
    if {[regexp {^(.*eskil)((?:\.[^/]+)?)(/src/.*)$} $this -> \
            pre ext post]} {
        if {$ext ne ".vfs"} {
            # If the unpacked vfs directory is available, read from that
            # instead.
            set src $pre.vfs$post
            if {[file readable $src]} {
                set this $src
            }
        }
    }
    puts "Resourcing $this"
    uplevel \#0 [list source $this]
    # Get all other source files
    InitReSource
}

# Initialize Ttk style settings
proc EskilThemeInit {} {
    # Import the 'default' theme border element.
    catch { ttk::style element create plain.border from default }
    catch { ttk::style element create plain.padding from default }
    catch { ttk::style element create plain.label from default }

    # Create a new style using the imported element.
    ttk::style layout My.Toolbutton {
        My.Toolbutton.plain.border -sticky nswe -children {
            My.Toolbutton.padding -sticky nswe -children {
                My.Toolbutton.label -sticky nswe
            }
        }
    }
    # Configure  our new style.
    ttk::style configure My.Toolbutton {*}[ttk::style configure Toolbutton] \
        -padding {1 1}
    ttk::style map My.Toolbutton {*}[ttk::style map Toolbutton] \
        -relief {disabled flat selected sunken pressed sunken active raised}
    # Re-do if the user changes theme.
    if {[lsearch -exact [bind . <<ThemeChanged>>] EskilThemeInit] == -1} {
        bind . <<ThemeChanged>> +EskilThemeInit
    }
}

proc defaultGuiOptions {} {
    # Turn off tearoff on all systems
    option add *Menu.tearOff 0
    if {[tk windowingsystem]=="x11"} {
        # Menubar looks out of place on linux. This adjusts the background
        # Which is enough to make it reasonable.
        set bg [ttk::style configure . -background]
        set sbg [ttk::style configure . -selectbackground]
        option add *Menubutton.background $bg
        option add *Menu.background $bg
        option add *Menu.activeBackground $sbg

        option add *Listbox.background $bg
        option add *Listbox.selectBackground $sbg
        option add *Text.background white
        option add *Text.selectBackground $sbg

        #option add *Scrollbar.takeFocus 0
        #option add *highlightThickness 0
    }
}

#####################################
# Startup stuff
#####################################

proc printUsage {} {
    puts {Usage: eskil [options] [files...]
  [options]  See below.
  [files...] Files to be compared

  If no files are given, the program is started anyway and you can select
  files from within. If only one file is given, the program looks for version
  control of the file, and if found, runs in version control mode.
  If directories are given, Eskil starts in directory diff.

  To list all options matching a prefix, run 'eskil --query prefix'.
  In tcsh use this line to get option completion:
  complete eskil 'C/-/`eskil --query -`/'

  Options:}

    # Dump option info
    foreach name [lsort -dictionary [dict keys $::eskil(opts,info)]] {
        set outName $name
        if {![dict exists $::eskil(opts,info) $name flag]} {
            puts "Internal Error: BOHOHOHO $name"
            break
        }
        if {![dict get $::eskil(opts,info) $name flag]} {
            append outName " <v>"
        }
        # Line up shorter ones
        if {[string length $outName] < 10} {
            set outName [format %-10s $outName]
        }
        set outName "$outName : "
        set indent [string length $outName]
        set len [expr {80 - $indent}]
        set d [dict get $::eskil(opts,info) $name shortdescr]
        if {$d eq "_"} continue
        while {$d ne ""} {
            if {[string length $d] <= $len} {
                set chunk $d
                set d ""
            } else {
                set ci $len
                while {[string index $d $ci] ne " " && $ci > 40} {
                    incr ci -1
                }
                set chunk [string range $d 0 $ci-1]
                set d [string trim [string range $d $ci end]]
            }
            puts "$outName$chunk"
            set outName [format %*s $indent ""]
        }
    }
}

#####################################
# Option/flag handling helpers
#####################################
# Validators
proc optValidatePdfColor {opt arg} {
    set fail 0
    if {![string is list $arg] || [llength $arg] != 3} {
        set fail 1
    } else {
        foreach val $arg {
            if {![string is double -strict $val] || $val < 0.0 || $val > 1.0} {
                set fail 1
            }
        }
    }
    if {$fail} {
        puts "Argument $opt must be a list of RBG values from 0.0 to 1.0"
        exit
    }
}
proc optValidatePositive {opt arg} {
    if {![string is double -strict $arg] || $arg <= 0} {
        puts "Argument $opt must be a positive number"
        exit
    }
}
proc optValidateNatural {opt arg} {
    if {![string is integer -strict $arg] || $arg < 0} {
        puts "Argument $opt must be a natural number"
        exit
    }
}
proc optValidatePaper {opt arg} {
    package require pdf4tcl
    if {[llength [pdf4tcl::getPaperSize $arg]] != 2} {
        puts "Argument $opt must be a valid paper size"
        puts "Valid paper sizes:"
        puts [join [lsort -dictionary [pdf4tcl::getPaperSizeList]] \n]
        exit
    }
}
proc optValidatePlugin {opt arg} {
    # We must start up completely to check a plugin
    Init
    set src [LocatePlugin $arg]
    if {$src eq ""} {
        puts "Bad plugin: $arg"
        printPlugins
        exit
    }
    # Look for declarations of command line options
    set ch [open $src r]
    while {[gets $ch line] >= 0} {
        # Only look until empty line
        if {[string trim $line] eq ""} break
        if {[regexp {^\#\# Option\s+(\S+)} $line -> name]} {
            addOpt $name
        }
        if {[regexp {^\#\# Flag\s+(\S+)} $line -> name]} {
            addFlags $name
        }
    }
    close $ch
}
# Option database setup
proc initOpts {} {
    set ::eskil(opts) {}
    set ::eskil(defoptinfo) {
        flag 0
        given 0
        multi 0
        type ""
        validator ""
        filter ""
        sideeffect ""
        shortdescr ""
        longdescr ""
    } 
}
# Add a command line flag that do not take a value
proc addFlags {args} {
    foreach name $args {
        dict set ::eskil(opts) $name 0
        dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
        dict set ::eskil(opts,info) $name flag  1
    }
}
# Document a flag
proc docFlag {name short {long {}}} {
    dict set ::eskil(opts,info) $name shortdescr $short
    dict set ::eskil(opts,info) $name longdescr $long
}

# Flag that affects Pref
proc addPrefFlag {name elem {value 1}} {
    dict set ::eskil(opts) $name 0
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
    dict set ::eskil(opts,info) $name flag  1
    dict set ::eskil(opts,info) $name type Pref
    dict set ::eskil(opts,info) $name "elem" $elem
    dict set ::eskil(opts,info) $name "value" $value
}
# Flag that affects local opts
proc addOptsFlag {name elem {value 1}} {
    dict set ::eskil(opts) $name 0
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
    dict set ::eskil(opts,info) $name flag  1
    dict set ::eskil(opts,info) $name type Opts
    dict set ::eskil(opts,info) $name "elem" $elem
    dict set ::eskil(opts,info) $name "value" $value
}
# Add a command line option that takes a value
proc addOpt {name {def ""}} {
    dict set ::eskil(opts) $name $def
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
}
# Add a command line option that takes a value and stores in Pref
proc addPrefOpt {name elem {validator ""}} {
    dict set ::eskil(opts) $name ""
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
    dict set ::eskil(opts,info) $name type Pref
    dict set ::eskil(opts,info) $name "elem" $elem
    dict set ::eskil(opts,info) $name "validator" $validator
}
# Add a vaildator command to an Opt
proc addValidator {name cmd} {
    dict set ::eskil(opts,info) $name validator $cmd
}
# Add a filter command prefix to an Opt
proc addFilter {name cmd} {
    dict set ::eskil(opts,info) $name filter $cmd
}
# Add a sideeffect to an Opt
##nagelfar syntax addSideEffect x c
proc addSideEffect {name script} {
    dict set ::eskil(opts,info) $name sideeffect $script
}
# Add a command line option that takes a value and stores in local opts
proc addOptsOpt {name elem {validator ""}} {
    dict set ::eskil(opts) $name ""
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
    dict set ::eskil(opts,info) $name type Opts
    dict set ::eskil(opts,info) $name "elem" $elem
    dict set ::eskil(opts,info) $name "validator" $validator
}
# Add a command line option that takes multiple values
proc addMultOpt {name} {
    dict set ::eskil(opts) $name {}
    dict set ::eskil(opts,info) $name $::eskil(defoptinfo)
    dict set ::eskil(opts,info) $name multi 1
}
# List all known options
proc allOpts {{pat *}} {
    return [dict keys $::eskil(opts) $pat]
}
proc optIsFlag {arg} {
    return [dict get $::eskil(opts,info) $arg flag]
}
proc optIsGiven {arg valName} {
    upvar 1 $valName val
    set val [dict get $::eskil(opts) $arg]
    return [dict get $::eskil(opts,info) $arg given]
}
proc optSet {arg val} {
    if {[dict get $::eskil(opts,info) $arg multi]} {
        dict lappend ::eskil(opts) $arg $val
    } else {
        dict set ::eskil(opts) $arg $val
    }
    # If it is a flag, the value can come from the settings
    if {[dict exists $::eskil(opts,info) $arg value]} {
        set val [dict get $::eskil(opts,info) $arg value]
    }
    # Any validator?
    set cmd [dict get $::eskil(opts,info) $arg validator]
    if {$cmd ne ""} {
        # The validator will exit if it fails
        $cmd $arg $val
    }
    # Any filter?
    set cmd [dict get $::eskil(opts,info) $arg filter]
    if {$cmd ne ""} {
        set val [{*}$cmd $val]
    }
    # Any side effect?
    set cmd [dict get $::eskil(opts,info) $arg sideeffect]
    if {$cmd ne ""} {
        uplevel 1 $cmd
    }

    set type [dict get $::eskil(opts,info) $arg type]
    switch $type {
        Pref {
            set ::Pref([dict get $::eskil(opts,info) $arg elem]) $val
        }
        Opts {
            upvar 1 opts _xx
            set _xx([dict get $::eskil(opts,info) $arg elem]) $val
        }
    }
    dict set ::eskil(opts,info) $arg given 1
}
proc optGet {arg} {
    return [dict get $::eskil(opts) $arg]
}

# Helper to add a file argument to list of files
proc cmdLineAddFile {filesName arg} {
    upvar 1 $filesName files
    set apa [file normalize [file join [pwd] $arg]]
    if {![file exists $apa]} {
        puts "Bad argument: $arg"
        exit
    } else {
        lappend files $apa
    }
}

# Go through all command line arguments and start the appropriate
# diff window.
# Returns the created toplevel.
# This can be used as an entry point if embedding eskil.
# In that case fill in ::eskil(argv) and ::eskil(argc) before calling.
proc parseCommandLine {} {
    global dirdiff

    set ::eskil(autoclose) 0
    set ::eskil(ignorenewline) 0
    set ::eskil(defaultopts) {}

    if {$::eskil(argc) == 0} {
        Init
        return [makeDiffWin]
    }

    # Set up all options info
    initOpts
    addFlags --help -help
    
    addPrefFlag -w          ignore -w
    addPrefFlag -b          ignore -b 
    addPrefFlag -noignore   ignore " "
    docFlag     -w          "Ignore all spaces"
    docFlag     -b          "Ignore space changes (default)"
    docFlag     -noignore   "Don't ignore any whitespace"
    addPrefFlag -noparse    parse 0
    addPrefFlag -line       parse 1
    addPrefFlag -smallblock parse 2
    addPrefFlag -block      parse 3
    docFlag -noparse    "No block analysis"
    docFlag -line       "Line based block analysis"
    docFlag -smallblock "Do block analysis on small blocks (default)"
    docFlag -block      "Full block analysis. This can be slow if there are large change blocks"

    addPrefFlag -char       lineparsewords 0
    addPrefFlag -word       lineparsewords 1
    docFlag     -char       "Character based change view (default)"
    docFlag     -word       "Word based change view"
    addPrefFlag -i          nocase
    addPrefFlag -nocase     nocase 
    docFlag     -i          "Ignore case changes"
    docFlag     -nocase     "Ignore case changes"
    addPrefFlag -nodigit    nodigit
    docFlag     -nodigit    "Ignore digit changes"
    addPrefFlag -nokeyword  dir,ignorekey
    docFlag     -nokeyword  "In directory diff, ignore \$ Keywords: \$"
    addPrefFlag -noempty    noempty
    docFlag     -noempty    "Ignore empty lines initially for matching"
    addPrefFlag -fine       finegrainchunks
    docFlag     -fine       "Use fine grained chunks. Useful for merging"
    addOptsFlag -table      view  table
    docFlag     -table      "Run in table mode"
    addOptsFlag -conflict mode conflict
    docFlag -conflict "Treat file as a merge conflict file and enter merge mode"
    # Conflict implies foreach
    addSideEffect -conflict {
        optSet -foreach 1
    }
    addFlags -dir -clip -patch -review -
    docFlag -dir    "Start in directory diff mode. Ignores other args"
    docFlag -clip   "Start in clip diff mode. Ignores other args"
    docFlag -patch  "View patch file"
    docFlag -       "Read patch file from standard input, to allow pipes"
    docFlag -review "View revision control tree as a patch."
    addFlags -browse -nodiff
    docFlag -browse "Automatically bring up file dialog after starting"
    docFlag -nodiff "Do not run diff after startup"
    addFlags -server -cvs -svn -debug
    docFlag -server "Set up Eskil to be controllable from the outside"
    docFlag -cvs    "Detect CVS first, if multiple version systems are used"
    docFlag -svn    "Detect SVN first, if multiple version systems are used"
    docFlag -debug  "Start in debug mode"
    addFlags -foreach -close
    docFlag -foreach "Open one diff window per file listed"
    docFlag -close   "Close windows with no changes"
    addFlags -nonewline -nonewline+ -nocdiff
    docFlag -nonewline  "Try to ignore newline changes"
    docFlag -nonewline+ "Try to ignore newline changes, and don't display"
    docFlag -nocdiff    "Disable C version of DiffUtil. For debug"
    addFlags -pluginlist -pluginallow
    docFlag -pluginlist  "List known plugins"
    docFlag -pluginallow "Allow full access privilege for a plugin"
    # Options that take values
    addOpt   -plugin
    docFlag  -plugin "Preprocess files using plugin"
    addValidator -plugin optValidatePlugin
    addOpt   -plugininfo
    docFlag  -plugininfo "Pass info to plugin (plugin specific)"
    addOpt   -plugindump
    docFlag  -plugindump "Dump plugin source to stdout"
    # These options affect Pref
    addPrefOpt -pivot             pivot             optValidatePositive
    docFlag    -pivot "Pivot setting for diff algorithm (100)"
    addPrefOpt -context           context           optValidateNatural
    docFlag    -context "Show only differences, with <n> lines of context"
    addPrefOpt -printHeaderSize   printHeaderSize   optValidatePositive
    addPrefOpt -printCharsPerLine printCharsPerLine optValidatePositive
    addPrefOpt -printPaper        printPaper        optValidatePaper
    addPrefOpt -printColorChange  printColorChange  optValidatePdfColor
    addPrefOpt -printColorOld     printColorOld     optValidatePdfColor  
    addPrefOpt -printColorNew     printColorNew     optValidatePdfColor
    addPrefOpt -printFont         printFont
    docFlag -printHeaderSize   "Font size for page header (10)"
    docFlag -printCharsPerLine "Adapt font size for this line length and wrap (80)"
    docFlag -printPaper       "Select paper size (a4)"
    docFlag -printColorChange "Color for change (1.0 0.7 0.7)"
    docFlag -printColorOld    "Color for old text (0.7 1.0 0.7)"
    docFlag -printColorNew    "Color for new text (0.8 0.8 1.0)"
    docFlag -printFont "Select font to use in PDF, afm or ttf. If <fontfile> is given as \"Courier\", PDF built in font is used"
    addMultOpt -prefix
    docFlag    -prefix "Care mainly about words starting with \"str\""
    addMultOpt -preprocess
    addMultOpt -preprocessleft
    addMultOpt -preprocessright
    docFlag    -preprocess  "TBW <pair>"
    docFlag    -preprocessleft  "TBW <pair>"
    docFlag    -preprocessright "TBW <pair>"
    # These affect opts
    addOptsOpt -limit    limitlines
    docFlag    -limit "Do not process more than <lines> lines"
    addOptsOpt -maxwidth maxwidth
    docFlag    -maxwidth "Limit column width in table mode"
    addOptsOpt -o mergeFile 
    docFlag    -o "Specify merge result output file"
    addFilter  -o [list file join [pwd]]
    addOptsOpt -a ancestorFile
    docFlag    -a "Give ancestor file for three way merge"
    addFilter  -a [list file join [pwd]]
    # Default is no ignore on three-way merge
    addSideEffect -a { set ::Pref(ignore) " " }
    addOptsOpt -sep separator
    docFlag -sep "See char <c> as separator between columns in files"
    # Handle if separator is given e.g. as '\t'
    addFilter  -sep [list subst -nocommands -novariables]
    addOptsOpt -print    printFile
    docFlag -print           "Generate PDF and exit."
    addOptsOpt -printpdf printFile ;# Old option
    docFlag -printpdf        "_"
    addSideEffect -print    { set opts(printFileCmd) 1 }
    addSideEffect -printpdf { set opts(printFileCmd) 1 }
    addMultOpt -r
    docFlag -r "Version info for version control mode"

    # If the first option is "--query", use it to ask about options.
    if {$::eskil(argc) == 2 && [lindex $::eskil(argv) 0] == "--query"} {
        set arg [lindex $::eskil(argv) 1]
        set allOpts [allOpts]
        if {[lsearch -exact $allOpts $arg] < 0} {
            set match [lsearch -glob -all -inline $allOpts $arg*]
        } else {
            set match [list $arg]
        }
        puts [lsort -dictionary $match]
        exit
    }

    # Go through and fill in options
    set files {}
    for {set i 0} {$i < [llength $::eskil(argv)]} {incr i} {
        set arg [lindex $::eskil(argv) $i]
        # Non-dash means not an option
        if {[string index $arg 0] ne "-"} {
            cmdLineAddFile files $arg
            continue
        }
        if {$arg eq "-"} {
            # Allow "-" for stdin patch processing
            lappend files "-"
            continue
        }
        # Take care of the special case of RCS style -r<rev>
        if {$arg ne "-review" && [string range $arg 0 1] eq "-r" && \
                    [string length $arg] > 2} {
            optSet -r [string range $arg 2 end]
            continue
        }
        # Handle unknowns
        if {![dict exists $::eskil(opts) $arg]} {
            # Try to see if it is an unique abbreviation of an option.
            set match [allOpts $arg*]
            if {[llength $match] == 1} {
                set arg [lindex $match 0]
            } else {
                # If not, try to put it among files
                cmdLineAddFile files $arg
                continue
            }
        }
        # Flags
        if {[optIsFlag $arg]} {
            set val 1
        } else {
            # Options with values
            incr i
            set val [lindex $::eskil(argv) $i]
        }
        optSet $arg $val
    }

    # Any help flag given just prints and exits
    if {[optIsGiven -help arg] || [optIsGiven --help arg]} {
        printUsage
        exit
    }

    # All options have been parsed, extract them to where they need to go

    # Straight to locals
    set plugin      [optGet -plugin]
    set plugininfo  [optGet -plugininfo]
    set plugindump  [optGet -plugindump]
    set pluginlist  [optGet -pluginlist]
    set pluginallow [optGet -pluginallow]
    set noautodiff  [optGet -nodiff]
    set nocdiff     [optGet -nocdiff]
    set dodir       [optGet -dir]
    set doclip      [optGet -clip]
    set dopatch     [optGet -patch]
    set doreview    [optGet -review]
    set autobrowse  [optGet -browse]
    set foreach     [optGet -foreach]
    set preferedRev "GIT"
    if {[optGet -svn]} {
        set preferedRev "SVN"
    } elseif {[optGet -cvs]} {
        set preferedRev "CVS"
    }

    # These directly correspond to ::eskil settings
    set apa {
        -nonewline  ignorenewline 1
        -nonewline+ ignorenewline 2
        -close      autoclose 1
        -debug      debug 1
    }
    foreach {opt elem val} $apa {
        if {[optIsGiven $opt arg]} {
            set ::eskil($elem) $val
        }
    }

    # Options that need individual checking/processing
    if {[optIsGiven -prefix arg]} {
        foreach apa $arg {
            set RE [string map [list % $apa] {^.*?\m(%\w+).*$}]
            if {$::Pref(nocase)} {
                set RE "(?i)$RE"
            }
            lappend ::Pref(preprocess) $RE {\1} ""
        }
    }
    if {[optIsGiven -preprocess arg]} {
        # FIXA: better validity check
        foreach apa $arg {
            foreach {RE sub} $apa {
                lappend ::Pref(preprocess) $RE $sub ""
            }
        }
    }
    if {[optIsGiven -preprocessleft arg]} {
        # FIXA: better validity check
        foreach apa $arg {
            foreach {RE sub} $apa {
                lappend ::Pref(preprocess) $RE $sub left
            }
        }
    }
    if {[optIsGiven -preprocessright arg]} {
        # FIXA: better validity check
        foreach apa $arg {
            foreach {RE sub} $apa {
                lappend ::Pref(preprocess) $RE $sub right
            }
        }
    }
    # Handle list of revisions
    if {[optIsGiven -r arg]} {
        set revNo 1
        foreach rev $arg {
            set opts(doptrev$revNo) $rev
            incr revNo
        }
    }
    if {[optGet -server]} {
        if {$::tcl_platform(platform) eq "windows"} {
            catch {
                package require dde
                dde servername Eskil
            }
        } else {
            package require Tk
            tk appname Eskil
        }
    }

    # Option handling done. Lets get started.

    Init

    if {$nocdiff} {
        DisableDiffUtilC
    }

    if {$pluginlist} {
        printPlugins
        exit
    }
    if {$plugindump ne ""} {
        printPlugin $plugindump
        exit
    }
    if {$plugin ne ""} {
        set pinterp [createPluginInterp $plugin $plugininfo $pluginallow pinfo]
        if {$pinterp eq ""} {
            # This should not happen since the validator should handle it
            puts "Bad plugin: $plugin"
            printPlugins
            exit
        }
        set opts(plugin) $pinterp
        set opts(pluginname) $plugin
        set opts(pluginallow) $pluginallow
        set opts(plugininfo) $plugininfo
        set opts(pluginpinfo) $pinfo
    }

    # Store the command line given opts
    set ::eskil(defaultopts) [array get opts]

    # Do we start in clip diff mode?
    if {$doclip} {
        return [makeClipDiffWin]
    }

    # Figure out if we start in a diff or dirdiff window.
    set len [llength $files]

    if {$len == 0 && $dodir} {
        set dirdiff(leftDir) ""
        set dirdiff(rightDir) ""
        return [makeDirDiffWin]
    }
    if {$len == 1} {
        set fullname [lindex $files 0]
        if {[FileIsDirectory $fullname 1]} {
            set dirdiff(leftDir) $fullname
            set dirdiff(rightDir) $dirdiff(leftDir)
            return [makeDirDiffWin]
        }
    } elseif {$len >= 2} {
        set fullname1 [lindex $files 0]
        set fullname2 [lindex $files 1]
        if {[FileIsDirectory $fullname1 1] && [FileIsDirectory $fullname2 1]} {
            set dirdiff(leftDir) $fullname1
            set dirdiff(rightDir) $fullname2
            return [makeDirDiffWin]
        }
    }

    # Ok, we have a normal diff
    set top [makeDiffWin]
    update

    # It is preferable to see the end if the rev string is too long
    $::widgets($top,rev1) xview end
    $::widgets($top,rev2) xview end

    if {$doreview} {
        set rev [detectRevSystem "" $preferedRev]
        set ::eskil($top,modetype) $rev
        set ::eskil($top,mode) "patch"
        set ::eskil($top,patchFile) ""
        set ::eskil($top,patchData) ""
        set ::eskil($top,reviewFiles) $files
        set ::Pref(toolbar) 1
        after idle [list doDiff $top]
        return $top
    }
    if {$len == 1 || $foreach} {
        set ReturnAfterLoop 0
        set first 1
        foreach file $files {
            if {$first} {
                set first 0
            } else {
                # Create new window for other files
                set top [makeDiffWin $top]
                update
                # It is preferable to see the end if the rev string is too long
                $::widgets($top,rev1) xview end
                $::widgets($top,rev2) xview end
            }
            set fullname $file
            set fulldir [file dirname $fullname]
            if {$::eskil($top,mode) eq "conflict"} {
                startConflictDiff $top $fullname
                after idle [list doDiff $top]
                set ReturnAfterLoop 1
                continue
            }
            if {!$autobrowse && !$dopatch} {
                # Check for revision control
                set rev [detectRevSystem $fullname $preferedRev]
                if {$rev ne ""} {
                    startRevMode $top $rev $fullname
                    if {$noautodiff} {
                        enableRedo $top
                    } else {
                        after idle [list doDiff $top]
                    }
                    set ReturnAfterLoop 1
                    continue
                }
            }
            # No revision control. Is it a patch file?
            set ::eskil($top,leftDir) $fulldir
            set ::eskil($top,leftFile) $fullname
            set ::eskil($top,leftLabel) $fullname
            set ::eskil($top,leftOK) 1
            if {$dopatch                                 || \
                    [regexp {\.(diff|patch)$} $fullname] || \
                    $fullname eq "-"} {
                set ::eskil($top,mode) "patch"
                set ::eskil($top,patchFile) $fullname
                set ::eskil($top,patchData) ""
                set autobrowse 0
                if {$noautodiff} {
                    enableRedo $top
                } else {
                    after idle [list doDiff $top]
                }
                set ReturnAfterLoop 1
                continue
            }
        }
        if {$ReturnAfterLoop} {return $top}
    } elseif {$len >= 2} {
        set fullname [file join [pwd] [lindex $files 0]]
        set fulldir [file dirname $fullname]
        set ::eskil($top,leftDir) $fulldir
        set ::eskil($top,leftFile) $fullname
        set ::eskil($top,leftLabel) $fullname
        set ::eskil($top,leftOK) 1
        set fullname [file join [pwd] [lindex $files 1]]
        set fulldir [file dirname $fullname]
        set ::eskil($top,rightDir) $fulldir
        set ::eskil($top,rightFile) $fullname
        set ::eskil($top,rightLabel) $fullname
        set ::eskil($top,rightOK) 1
        if {$noautodiff} {
            enableRedo $top
        } else {
            after idle [list doDiff $top]
        }
    }
    if {$autobrowse && (!$::eskil($top,leftOK) || !$::eskil($top,rightOK))} {
        if {!$::eskil($top,leftOK) && !$::eskil($top,rightOK)} {
            openBoth $top 0
        } elseif {!$::eskil($top,leftOK)} {
            openLeft $top
        } elseif {!$::eskil($top,rightOK)} {
            openRight $top
        }
        # If we cancel the second file and detect CVS, ask about it.
        # TBD: Extend this to all VCS:s?
        if {$::eskil($top,leftOK) && !$::eskil($top,rightOK) && \
                [llength [glob -nocomplain [file join $fulldir CVS]]]} {

            if {[tk_messageBox -title Diff -icon question \
                    -message "Do CVS diff?" -type yesno] eq "yes"} {
                set fullname $::eskil($top,leftFile)
                set ::eskil($top,leftOK) 0
                startRevMode $top "CVS" $fullname
                after idle [list doDiff $top]
            }
        }
    }
    return $top
}

# Save options to file ~/.eskilrc
proc saveOptions {top} {
    # Is this a diff win or some other win?
    if {[info exists ::widgets($top,wDiff1)]} {
        # Check if the window size has changed
        set w $::widgets($top,wDiff1)
        if {[winfo reqwidth $w] != [winfo width $w] || \
                    [winfo reqheight $w] != [winfo height $w]} {
            set dx [expr {[winfo width $w] - [winfo reqwidth $w]}]
            set dy [expr {[winfo height $w] - [winfo reqheight $w]}]
            set cx [font measure myfont 0]
            set cy [font metrics myfont -linespace]
            set neww [expr {[$w cget -width]  + $dx / $cx}]
            set newh [expr {[$w cget -height] + $dy / $cy}]
            if {$neww != $::Pref(linewidth) || $newh != $::Pref(lines)} {
                set msg "Should I save the current window\
                    size with the preferences?\nCurrent: $neww x $newh  Old:\
                    $::Pref(linewidth) x $::Pref(lines)"
                set apa [tk_messageBox -title "Save Preferences" \
                                 -icon question -type yesno -message $msg]
                if {$apa == "yes"} {
                    set ::Pref(linewidth) $neww
                    set ::Pref(lines) $newh
                }
            }
        }
    }

    set rcfile "~/.eskilrc"
    if {[catch {set ch [open $rcfile "w"]} err]} {
        tk_messageBox -icon error -title "File error" -message \
                "Error when trying to save preferences:\n$err"
        return
    }

    foreach i [array names ::Pref] {
        # Skip unchanged options.
        if {[info exists ::DefaultPref($i)]} {
            if {$::DefaultPref($i) eq $::Pref($i)} {
                continue
            }
            puts $ch "# $i default : $::DefaultPref($i)"
        }
        puts $ch [list set "::Pref($i)" $::Pref($i)]
    }
    close $ch

    tk_messageBox -icon info -title "Saved" -message \
            "Preferences saved to:\n[file nativename $rcfile]"
}

proc getOptions {} {
    if {$::tcl_platform(os) eq "Darwin"} {
        set ::DefaultPref(fontsize) 10
    } else {
        set ::DefaultPref(fontsize) 8
    }
    # Maybe change to TkFixedFont in 8.5 ?
    set ::DefaultPref(fontfamily) Courier
    set ::DefaultPref(ignore) "-b"
    set ::DefaultPref(nocase) 0
    set ::DefaultPref(noempty) 0
    set ::DefaultPref(pivot) 100
    set ::DefaultPref(nodigit) 0
    set ::DefaultPref(parse) 2
    set ::DefaultPref(lineparsewords) 0
    set ::DefaultPref(colorequal) ""
    set ::DefaultPref(colorchange) red
    set ::DefaultPref(colornew1) darkgreen
    set ::DefaultPref(colornew2) blue
    set ::DefaultPref(bgequal) ""
    set ::DefaultPref(bgchange) \#ffe0e0
    set ::DefaultPref(bgnew1) \#a0ffa0
    set ::DefaultPref(bgnew2) \#e0e0ff
    set ::DefaultPref(context) -1
    set ::DefaultPref(finegrainchunks) 0
    set ::DefaultPref(marklast) 1
    set ::DefaultPref(linewidth) 80
    set ::DefaultPref(lines) 60
    set ::DefaultPref(editor) ""
    set ::DefaultPref(preprocess) {}
    set ::DefaultPref(toolbar) 0
    set ::DefaultPref(wideMap) 0 ;# Not settable in GUI yet

    # Print options
    set ::DefaultPref(printHeaderSize) 10
    set ::DefaultPref(printCharsPerLine) 80
    set ::DefaultPref(printPaper) a4
    set ::DefaultPref(printColorChange) "1.0 0.7 0.7"
    set ::DefaultPref(printColorNew1)   "0.7 1.0 0.7"
    set ::DefaultPref(printColorNew2)   "0.8 0.8 1.0"
    set ::DefaultPref(printFont) ""

    # Directory diff options
    set ::DefaultPref(dir,comparelevel) 1
    set ::DefaultPref(dir,ignorekey) 0
    set ::DefaultPref(dir,incfiles) ""
    set ::DefaultPref(dir,exfiles) "*.o"
    set ::DefaultPref(dir,incdirs) ""
    set ::DefaultPref(dir,exdirs) "RCS CVS .git .svn .hg"
    set ::DefaultPref(dir,onlyrev) 0
    set ::DefaultPref(dir,nice) 1

    # Start with default preferences, before loading setup file
    array set ::Pref [array get ::DefaultPref]

    # Backward compatibilty options
    set ::Pref(onlydiffs) -1
    set ::Pref(regsub) {}

    set ::eskil(filter) ""

    if {![info exists ::eskil_testsuite] && [file exists "~/.eskilrc"]} {
        safeLoad "~/.eskilrc" ::Pref
    }

    if {$::Pref(editor) ne ""} {
        set ::util(editor) $::Pref(editor)
    }

    # If the user's file has this old option, translate it to the new
    if {$::Pref(onlydiffs) == 0} {
        set ::Pref(context) -1
    }
    unset ::Pref(onlydiffs)
    if {$::Pref(regsub) ne ""} {
        foreach {a b} $::Pref(regsub) {
            lappend ::Pref(preprocess) $a $b ""
        }
    }
    unset ::Pref(regsub)

    # Set up reactions to some Pref settings
    if {![info exists ::widgets(toolbars)]} {
        set ::widgets(toolbars) {}
    }
    trace add variable ::Pref(toolbar) write TraceToolbar
}

proc TraceToolbar {args} {
    # FIXA: Handle destroyed windows ?
    foreach __ $::widgets(toolbars) {
        if {$::Pref(toolbar)} {
            grid configure $__
        } else {
            grid remove $__
        }
    }
}

# Global code is only run the first time to be able to reread source
if {![info exists ::eskil(gurkmeja)]} {
    set ::eskil(gurkmeja) 1

    package require pstools
    namespace import -force pstools::*
    getOptions
    if {![info exists ::eskil_testsuite]} {
        parseCommandLine
    }
}
Changes to tests/all.tcl.
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
}

package require Tk
wm withdraw .

set ::eskil_testsuite 1

if {[file exists eskil.vfs/src/eskil.tcl_i]} {
    puts "Running with code coverage"
    source eskil.vfs/src/eskil.tcl_i
} else {
    source eskil.vfs/src/eskil.tcl
}
Init

# Helpers to temporarily stub things out
set ::stubs {}
proc stub {name argv body} {
    if {[info commands _stub_$name] eq ""} {







|

|

|







21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
}

package require Tk
wm withdraw .

set ::eskil_testsuite 1

if {[file exists eskil.vfs/src/startup.tcl_i]} {
    puts "Running with code coverage"
    source eskil.vfs/src/startup.tcl_i
} else {
    source eskil.vfs/src/startup.tcl
}
Init

# Helpers to temporarily stub things out
set ::stubs {}
proc stub {name argv body} {
    if {[info commands _stub_$name] eq ""} {