This file is indexed.

/usr/share/perl5/Tk/Pod/Text.pm is in libtk-pod-perl 0.9942-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
require 5;
package Tk::Pod::Text;

use strict;

BEGIN {  # Make a DEBUG constant very first thing...
  if(defined &DEBUG) {
  } elsif(($ENV{'TKPODDEBUG'} || '') =~ m/^(\d+)/) { # untaint
    my $debug = $1;
    *DEBUG = sub () { $debug };
  } else {
    *DEBUG = sub () {0};
  }
}

use Carp;
use Config;
use Tk qw(catch);
use Tk::Frame;
use Tk::Pod;
use Tk::Pod::SimpleBridge;
use Tk::Pod::Cache;
use Tk::Pod::Util qw(is_in_path is_interactive detect_window_manager start_browser);

use vars qw($VERSION @ISA @POD $IDX
	    @tempfiles @gv_pids $terminal_fallback_warn_shown);

$VERSION = '5.31';

@ISA = qw(Tk::Frame Tk::Pod::SimpleBridge Tk::Pod::Cache);

BEGIN { DEBUG and warn "Running ", __PACKAGE__, "\n" }

Construct Tk::Widget 'PodText';

BEGIN {
  unshift @POD, (
   @INC,
   $ENV{'PATH'} ?
     grep(-d, split($Config{path_sep}, $ENV{'PATH'}))
    : ()
  );
  $IDX = undef;
  DEBUG and warn "POD: @POD\n";
};

{
    package # hide from CPAN indexer
	Tk::Pod::Text::_HistoryEntry;

    use File::Basename qw(basename);

    for my $member (qw(file text index pod_title)) {
	my $sub = sub {
	    my $self = shift;
	    if (@_) {
		$self->{$member} = $_[0];
	    }
	    $self->{$member};
	};
	no strict 'refs';
	*{$member} = $sub;
    }

    sub create {
	my($class,$what,$index) = @_;
	my $o = bless {}, $class;
	if (ref $what eq 'HASH') {
	    $o->file($what->{file});
	    $o->text($what->{text});
	} else {
	    $o->file($what);
	}
	$o->index($index);
	$o;
    }

    sub get_label {
	my $self = shift;
	my $pod_title = $self->pod_title;
	return $pod_title if defined $pod_title;
	my $file = $self->file;
	return basename $file if defined $file;
	return "<Untitled document>";
    }
}

use constant HISTORY_DIALOG_ARGS => [-icon => 'info',
				     -title => 'History Error',
				     -type => 'OK'];
sub Dir
{
 my $class = shift;
 unshift(@POD,@_);
}

sub Find
{
 my ($file) = @_;
 return $file if (-f $file);
 my $dir;
 foreach $dir ("",@POD)
  {
   my $prefix;
   foreach $prefix ("","pod/","pods/")
    {
     my $suffix;
     foreach $suffix (".pod",".pm",".pl","")
      {
       my $path = "$dir/" . $prefix . $file . $suffix;
       return $path if (-r $path && -T $path);
       $path =~ s,::,/,g;
       return $path if (-r $path && -T $path);
      }
    }
  }
  return undef;
}

sub findpod {
    my ($w,$name,%opts) = @_;
    my $quiet = delete $opts{-quiet};
    warn "Unhandled extra options: ". join " ", %opts
	if %opts;
    unless (defined $name and length $name) {
	return if $quiet;
	$w->_die_dialog("Empty Pod file/name");
    }

    my $absname;
    if (-f $name) {
	$absname = $name;
    } else {
	if ($name !~ /^[-_+:.\/A-Za-z0-9]+$/) {
	    return if $quiet;
	    $w->_die_dialog("Invalid path/file/module name '$name'\n");
	}
	$absname = Find($name);
    }
    if (!defined $absname) {
	return if $quiet;
	$w->_error_dialog("Can't find Pod '$name'\n");
	die "Can't find Pod '$name' in @POD\n";
    }
    if (eval { require File::Spec; File::Spec->can("rel2abs") }) {
	DEBUG and warn "Turn $absname into an absolute file name";
	$absname = File::Spec->rel2abs($absname);
    }
    $absname;
}

sub _remember_old {
    my $w = shift;
    for (qw(File Text)) {
	$w->{"Old$_"} = $w->{$_};
    }
}

sub _restore_old {
    my $w = shift;
    for (qw(File Text)) {
	$w->{$_} = $w->{"Old$_"};
    }
}

sub file {   # main entry point
  my $w = shift;
  if (@_)
    {
      my $file = shift;
      $w->_remember_old;
      eval {
	  my $calling_from_history = $w->privateData()->{'from_history'};
	  $w->{'File'} = $file;
	  $w->{'Text'} = undef;
	  my $path = $w->findpod($file);
	  if (!$calling_from_history) {
	      $w->history_modify_entry;
	      $w->history_add({file => $path}, "1.0");
	  }
	  $w->configure('-path' => $path);
	  $w->delete('1.0' => 'end');
	  my $tree_sw = $w->parent->Subwidget("tree");
	  if ($tree_sw) {
	      $tree_sw->SeePath("file:$path");
	  }
	  my $t;
	  if (DEBUG) {
	      require Benchmark;
	      $t = Benchmark->new;
	  }
	  if (!$w->get_from_cache) {
	      $w->process($path);
	      $w->add_to_cache; # XXX pass time for processing?
	      if (!$calling_from_history) {
		  $w->history_modify_current_title; # now the pod_title is known
	      }
	  }
	  if (defined $t) {
	      print Benchmark::timediff(Benchmark->new, $t)->timestr,"\n";
	  }
	  $w->focus;
      };
      if ($@) {
	  $w->_restore_old;
	  die $@;
      }
    }
  $w->{'File'};
}

sub text {
  my $w = shift;
  if (@_)
    {
      my $text = shift;
      $w->_remember_old;
      eval {
	  my $calling_from_history = $w->privateData()->{'from_history'};
	  $w->{'Text'} = $text;
	  $w->{'File'} = undef;
	  if (!$calling_from_history) {
	      $w->history_modify_entry;
	      $w->history_add({text => $text}, "1.0");
	  }
	  $w->configure('-path' => undef);
	  $w->delete('1.0' => 'end');
## XXX Implementation unclear, maybe should be done in showcommand call...
#	  my $tree_sw = $w->parent->Subwidget("tree");
#	  if ($tree_sw) {
#	      $tree_sw->SeeFunc("file:$path");
#	  }
	  my $t;
	  if (DEBUG) {
	      require Benchmark;
	      $t = Benchmark->new;
	  }
	  # No caching here
	  # XXX title: the 2nd part of the hack
	  my $title = $w->cget(-title);
	  $w->process(\$text, $title);
	  if (!$calling_from_history) {
	      $w->history_modify_current_title; # now the pod_title is known
	  }
	  if (defined $t) {
	      print Benchmark::timediff(Benchmark->new, $t)->timestr,"\n";
	  }
	  $w->focus;
      };
      if ($@) {
	  $w->_restore_old;
	  die $@;
      }
    }
  $w->{'Text'};
}

sub reload
{
 my ($w) = @_;
 # remember old y position
 my ($currpos) = $w->yview;
 $w->delete('0.0','end');
 $w->delete_from_cache;
 $w->process($w->cget('-path'));
 # restore old y position
 $w->yview(moveto => $currpos);
 # set (invisible) insertion cursor into the visible text area
 $w->markSet(insert => '@0,0');
}

# Works also for viewing source code
sub _get_editable_path
{
 my ($w) = @_;
 my $path = $w->cget('-path');
 if (!defined $path)
  {
   my $text = $w->cget("-text");
   $w->_need_File_Temp;
   my($fh,$fname) = File::Temp::tempfile(UNLINK => 1,
					 SUFFIX => "_tkpod.pod");
   print $fh $text;
   close $fh;
   $path = $fname;
  }
 $path;
}

sub edit
{
 my ($w,$edit,$linenumber) = @_;
 my $path = $w->_get_editable_path;
 if (!defined $edit)
  {
   $edit = $ENV{TKPODEDITOR};
  }
 if ($^O eq 'MSWin32')
  {
   if (defined $edit && $edit ne "")
    {
     system(1, $edit, $path);
    }
   else
    {
     system(1, "ptked", $path);
    }
  }
 else
  {
   if (!defined $edit || $edit eq "")
    {
     # VISUAL and EDITOR are supposed to have a terminal, but tkpod can
     # be started without a terminal.
     my $isatty = is_interactive();
     if (!$isatty)
      {
       if (!defined $edit || $edit eq "")
        {
         $edit = $ENV{XEDITOR};
        }
       if (!defined $edit || $edit eq "")
        {
         if (!$terminal_fallback_warn_shown)
	  {
           $w->_warn_dialog("No terminal and neither TKPODEDITOR nor XEDITOR environment variables set. Fallback to ptked.");
	   $terminal_fallback_warn_shown = 1;
          }
         $edit = 'ptked';
        }
      }
     else
      {
       $edit = $ENV{VISUAL} || $ENV{'EDITOR'} || '/usr/bin/vi';
      }
    }

   if (defined $edit)
    {
     if (fork)
      {
       wait; # parent
      }
     else
      {
       #child
       if (fork)
        {
         # still child
         exec("true");
        }
       else
        {
         # grandchild
	 if (defined $linenumber && $edit =~ m{\bemacsclient\b}) # XXX an experiment, maybe support more editors?
	  {
	   exec("$edit +$linenumber $path");
          }
	 else
	  {
           exec("$edit $path");
          }
        }
      }
    }
  }
}

sub edit_get_linenumber
{
 my($w) = @_;
 my $linenumber = $w->get_linenumber;
 $w->edit(undef, $linenumber);
}

sub get_linenumber
{
 my($w) = @_;
 for my $tag ($w->tagNames('@' . ($w->{MenuX} - $w->rootx) . ',' . ($w->{MenuY} - $w->rooty)))
  {
   if ($tag =~ m{start_line_(\d+)})
    {
     return $1;
    }
  }
 undef;
}

sub view_source
{
 my($w) = @_;
 # XXX why is -title empty here?
 my $title = $w->cget(-title) || $w->cget('-file');
 my $t = $w->Toplevel(-title => "Source of $title - Tkpod");
 my $font_size = $w->base_font_size;
 my $more = $t->Scrolled('More',
			 -font => "Courier $font_size",
			 -scrollbars => $Tk::platform eq 'MSWin32' ? 'e' : 'w',
			)->pack(-fill => "both", -expand => 1);
 $more->Load($w->_get_editable_path);
 my $linenumber = $w->get_linenumber;
 if (defined $linenumber)
  {
   $more->see($linenumber.'.'.0);
  }
 $more->AddQuitBindings;
 $more->focus;
}

sub copy_pod_location
{
 my($w) = @_;
 my $file = $w->_get_editable_path;
 if (!defined $file)
  {
   $w->_error_dialog("Cannot copy location: this Pod is not associated with a file");
   return;
  }
 $w->SelectionOwn;
 $w->SelectionHandle(sub {
			 my($offset,$maxbytes) = @_;
			 # XXX It's not exactly clear why I have to
			 # call _get_editable_path again here and not
			 # reuse $file.
			 my $file = $w->_get_editable_path;
			 return undef if $offset > length($file);
			 substr($file, $offset, $maxbytes);
		     });
}

sub _sgn { $_[0] cmp 0 }

sub zoom_normal {
    my $w = shift;
    $w->adjust_font_size($w->standard_font_size);
    $w->clear_cache;
}

# XXX should use different increments for different styles
sub zoom_out {
    my $w = shift;
    $w->adjust_font_size($w->base_font_size - 1 * _sgn($w->base_font_size));
    $w->clear_cache;
}

sub zoom_in {
    my $w = shift;
    $w->adjust_font_size($w->base_font_size + 1 * _sgn($w->base_font_size));
    $w->clear_cache;
}

sub More_Widget { "More" }
sub More_Module { "Tk::More" }

sub Populate
{
    my ($w,$args) = @_;

    if ($w->More_Module) {
	eval q{ require } . $w->More_Module;
	die $@ if $@;
    }

    $w->SUPER::Populate($args);

    $w->privateData()->{history} = [];
    $w->privateData()->{history_index} = -1;

    my $p = $w->Scrolled($w->More_Widget,
			 -helpcommand => sub {
			     $w->parent->help if $w->parent->can('help');
			 },
			 -scrollbars => $Tk::platform eq 'MSWin32' ? 'e' : 'w');
    my $p_scr = $p->Subwidget('scrolled');
    $w->Advertise('more' => $p_scr);
    $p->pack(-expand => 1, -fill => 'both');

    # XXX Subwidget stuff needed because Scrolled does not
    #     delegate bind, bindtag to the scrolled widget. Tk402.* (and before?)
    #	  (patch posted and included in Tk402.004)
    $p_scr->bindtags([$p_scr, $p_scr->bindtags]);
    $p_scr->bind('<Double-1>',       sub  { $w->DoubleClick($_[0]) });
    $p_scr->bind('<Shift-Double-1>', sub  { $w->ShiftDoubleClick($_[0]) });
    $p_scr->bind('<Double-2>',       sub  { $w->ShiftDoubleClick($_[0]) });
    $p_scr->bind('<3>',              sub  { $w->PostPopupMenu($p_scr, $w->pointerxy) });
    $p_scr->bind('<ButtonRelease-2>', [sub {
					   # A hack solution to prevent from firing this
					   # event over pod links. See http://wiki.tcl.tk/6101
					   my($ro,$x,$y) = @_;
					   if (grep { $_ eq 'pod_link' } $ro->tagNames("\@$x,$y")) {
					       Tk->break;
					   } else {
					       $w->OpenPodBySelection;
					   }
				       }, Tk::Ev("x"), Tk::Ev("y")]);

    $p->configure(-font => $w->Font(family => 'courier'));

    $p->tag('configure','text', -font => $w->Font(family => 'times'));

    $p->insert('0.0',"\n");

    $w->{List}   = []; # stack of =over
    $w->{Item}   = undef;
    $w->{'indent'} = 0;
    $w->{Length}  = 64;
    $w->{Indent}  = {}; # tags for various indents

    # Seems like a perl bug: ->can() does not work before actually calling
    # the subroutines (perl5.6.0 isa bug?)
    eval {
	$p->EditMenuItems;
	$p->SearchMenuItems;
	$p->ViewMenuItems;
    };

    my $m = $p->Menu
	(-title => "Tkpod",
	 -tearoff => $Tk::platform ne 'MSWin32',
	 -menuitems =>
	 [
	  [Button => 'Back',     -command => [$w, 'history_move', -1]],
	  [Button => 'Forward',  -command => [$w, 'history_move', +1]],
	  [Button => 'Reload',   -command => sub{$w->reload} ],
	  [Button => 'Edit Pod',       -command => sub{ $w->edit_get_linenumber } ],
	  [Button => 'View source',    -command => sub{ $w->view_source } ],
	  [Button => 'Copy Pod location', -command => sub { $w->copy_pod_location } ],
	  [Button => 'Search full text',-command => ['SearchFullText', $w]],
	  [Separator => ""],
	  [Cascade => 'Edit',
	   ($Tk::VERSION > 800.015 && $p->can('EditMenuItems') ? (-menuitems => $p->EditMenuItems) : ()),
	  ],
	  [Cascade => 'Search',
	   ($Tk::VERSION > 800.015 && $p->can('SearchMenuItems') ? (-menuitems => $p->SearchMenuItems) : ()),
	  ],
	  [Cascade => 'View',
	   ($Tk::VERSION > 800.015 && $p->can('ViewMenuItems') ? (-menuitems => $p->ViewMenuItems) : ()),
	  ]
	 ]);
    eval { $p->menu($m) }; warn $@ if $@;

    $w->Delegates(DEFAULT => $p,
		  'SearchFullText' => 'SELF',
		 );

    $w->ConfigSpecs(
            '-file'       => ['METHOD'  ],
            '-text'       => ['METHOD'  ],
            '-path'       => ['PASSIVE' ],
            '-poddone'    => ['CALLBACK'],
	    '-title'      => ['PASSIVE' ], # XXX unclear

            '-wrap'       => [ $p, qw(wrap       Wrap       word) ],
	    # -font ignored because it does not change the other fonts
	    #'-font'	  => [ 'PASSIVE', undef, undef, undef],
            '-scrollbars' => [ $p, qw(scrollbars Scrollbars), $Tk::platform eq 'MSWin32' ? 'e' : 'w' ],
	    '-basefontsize' => ['METHOD'], # XXX may change

            'DEFAULT'     => [ $p ],
            );

    $args->{-width} = $w->{Length};
}

sub basefontsize
{
 my($w, $val) = @_;
 if ($val)
  {
   $w->set_base_font_size($val);
  } 
 else
  {
   $w->base_font_size;
  }
}

sub Font
{
 my ($w,%args)    = @_;
 $args{'family'}  = 'times'  unless (exists $args{'family'});
 $args{'weight'}  = 'medium' unless (exists $args{'weight'});
 $args{'slant'}   = 'r'      unless (exists $args{'slant'});
 $args{'size'}    = 140      unless (exists $args{'size'});
 $args{'spacing'} = '*'     unless (exists $args{'spacing'});
 $args{'slant'}   = substr($args{'slant'},0,1);
 my $name = "-*-$args{'family'}-$args{'weight'}-$args{'slant'}-*-*-*-$args{'size'}-*-*-$args{'spacing'}-*-iso8859-1";
 return $name;
}

sub ShiftDoubleClick {
    shift->DoubleClick(shift, 'new');
}

sub DoubleClick
{
 my ($w,$ww,$how) = @_;
 my $Ev = $ww->XEvent;
 $w->SelectToModule($Ev->xy);
 my $sel = catch { $w->SelectionGet };
 if (defined $sel)
  {
   my $file;
   if ($file = $w->findpod($sel)) {
       if (defined $how && $how eq 'new')
	{
	 my $tree = eval { $w->parent->cget(-tree) };
	 my $exitbutton = eval { $w->parent->cget(-exitbutton) };
         $w->MainWindow->Pod('-file' => $sel,
			     '-tree' => $tree,
			     -exitbutton => $exitbutton);
	}
       else
	{
         $w->configure('-file'=>$file);
        }
   } else {
       $w->_die_dialog("No Pod documentation found for '$sel'\n");
   }
  }
 Tk->break;
}

sub Link
{
 my ($w,$how,$index,$man,$sec) = @_;

 # If clicking on a Link, the <Leave> binding is never called, so it
 # have to be done here:
 $w->LeaveLink;

 $man = '' unless defined $man;
 $sec = '' unless defined $sec;

 if ($how eq 'reuse' && $man ne '')
  {
   my $file = $w->cget('-file');
   $w->configure('-file' => $man)
    unless ( defined $file and ($file =~ /\Q$man\E\.\w+$/ or $file eq $man) );
  }

 if ($how eq 'new')
  {
   $man = $w->cget('-file') if ($man eq "");
   my $tree = eval { $w->parent->cget(-tree) };
   my $exitbutton = eval { $w->parent->cget(-exitbutton) };
   my $old_w = $w;
   my $new_pod = $w->MainWindow->Pod('-tree' => $tree,
				     -exitbutton => $exitbutton,
				    );
   $new_pod->configure('-file' => $man); # see tkpod for the same problem

   $w = $new_pod->Subwidget('pod');
   # set search term for new window
   my $search_term_ref = $old_w->Subwidget('more')->Subwidget('searchentry')->cget(-textvariable);
   if (defined $$search_term_ref && $$search_term_ref ne "") {
       $ {$w->Subwidget('more')->Subwidget('searchentry')->cget(-textvariable) } = $$search_term_ref;
   }
  }
  # XXX big docs like Tk::Text take too long until they return

 if ($sec ne '' && $man eq '') # XXX reuse vs. new
  {
   $w->history_modify_entry;
  }

 if ($sec ne '')
  {

   my $highlight_match = sub
    {
     my $start = shift;
     my($line) = split(/\./, $start);
     $w->tag('remove', '_section_mark', qw/0.0 end/);
     $w->tag('add', '_section_mark',
	     $line . ".0",
	     $line . ".0 lineend");
     $w->yview("_section_mark.first");
     $w->after(500, [$w, qw/tag remove _section_mark 0.0 end/]);
    };

   DEBUG and warn "Looking for section \"$sec\" across Sections entries...\n";

   foreach my $s ( @{$w->{'sections'} || []} )
    {
     if($s->[1] eq $sec)
      {
       DEBUG and warn " $sec is $$s[1] (at $$s[2])\n";
       my $start = $s->[2];
       my($line) = split(/\./, $start);
       $line--; # off by one, why?
       $highlight_match->("$line.0");
       return;
      }
     else
      {
       DEBUG > 2 and warn " Nope, it's not $$s[1] (at $$s[2])\n";
      }
    }

   my $start = ($w->tag('nextrange',$sec, '1.0'))[0];

   if (defined $start)
    {
     DEBUG and warn " Found at $start\n";
     $highlight_match->($start);
     return;
    }
   else
    {
     DEBUG and warn " Not found so far.  Using a quoted nextrange search...\n";
     my $link = ($man || '') . $sec;
     $start = ($w->tag('nextrange',"\"$link\"",'1.0'))[0];
    }

   if (defined $start)
    {
     DEBUG and warn " Found at $start\n";
     $highlight_match->($start);
     return;
    }
   else
    {
     DEBUG and warn " Again not found.  Using an exact search at line beginnings...\n";
     $start = $w->search(qw/-regexp -nocase --/, qr{^\s*\Q$sec}, '1.0');
    }

   if (defined $start) 
    {
     DEBUG and warn " Found at $start\n";
     $highlight_match->($start);
     return;
    }
   else
    {
     DEBUG and warn " Again not found.  Using an exact search...\n";
     $start = $w->search(qw/-exact -nocase --/, $sec, '1.0');
    }

   if (defined $start)
    {
     DEBUG and warn " Found at $start\n";
     $highlight_match->($start);
     return;
    }
   else
    {
     DEBUG and warn " Not found! (\"sec\")\n";
     $w->_die_dialog("Section '$sec' not found\n");
    }
   DEBUG and warn "link-zapping to $start linestart\n";
   $w->yview("$start linestart");
  }

 if ($sec ne '' && $man eq '') # XXX reuse vs. new
  {
   $w->history_add({file => $w->cget(-path)}, $w->index('@0,0'));
  }

}

sub Link_url {
    my ($w,$how,$index,$man,$sec) = @_;
    if (my($lat,$lon) = $man =~ m{^geo:([^,]+),([^,]+)}) {
        DEBUG and warn "Translate geo URI $man\n";
        # XXX currently hardcoded to Wikipedia's GeoHack page, maybe make
        # configurable
        my $ddd2dms = sub {
            my($ddd) = @_;
	    my $north_east = $ddd >= 0;
	    $ddd = -$ddd if !$north_east;
	    my $deg = int($ddd);
	    my $min = ($ddd-$deg)*60;
	    my $sec = ($min-int($min))*60;
	    $min = int($min);
	    (($north_east ? $deg : -$deg), $min, $sec);
	};
	my $lat_sgn = $lat < 0 ? do { $lat *= -1; "S" } : "N";
	my $lon_sgn = $lon < 0 ? do { $lon *= -1; "W" } : "E";
        $man = "http://toolserver.org/~geohack/geohack.php?params="
	    . join("_", $ddd2dms->($lat), $lat_sgn, $ddd2dms->($lon), $lon_sgn);
    }
    DEBUG and warn "Start browser with $man\n";
    start_browser($man);
}

sub Link_man {
    my ($w,$how,$index,$man,$sec) = @_;
    my $mansec;
    if ($man =~ s/\s*\((.*)\)\s*$//) {
	$mansec = $1;
    }
    my @manbrowser;
    if (exists $ENV{TKPODMANVIEWER} && $ENV{TKPODMANVIEWER} eq "internal") {
	DEBUG and warn "Use internal man viewer\n";
    } else {
	my $manurl = "man:$man($mansec)";
	if (defined $sec && $sec ne "") {
	    $manurl .= "#$sec";
	}
	DEBUG and warn "Try to start any man browser for $manurl\n";
	@manbrowser = ('gnome-help-browser', 'khelpcenter');
	my $wm = detect_window_manager($w);
	DEBUG and warn "Window manager system is $wm\n";
	if ($wm eq 'kde') {
	    unshift @manbrowser, 'khelpcenter';
	}
	if (defined $ENV{TKPODMANVIEWER}) {
	    unshift @manbrowser, $ENV{TKPODMANVIEWER};
	}
	for my $manbrowser (@manbrowser) {
	    DEBUG and warn "Try $manbrowser...\n";
	    if (is_in_path($manbrowser)) {
		if (fork == 0) {
		    DEBUG and warn "Use $manbrowser...\n";
		    exec($manbrowser, $manurl);
		    die $!;
		}
		return;
	    }
	}
    }
    if (!$w->InternalManViewer($mansec, $man)) {
	$w->_die_dialog("No useable man browser found. Tried @manbrowser and internal man viewer via `man'");
    }
}

sub InternalManViewer {
    my($w, $mansec, $man) = @_;
    my $man_exe = "man";
    if (!is_in_path($man_exe)) {
	if ($^O eq 'MSWin32') {
	    $man_exe = "c:/cygwin/bin/man.exe";
	    if (!-e $man_exe) {
		return 0;
	    }
	} else {
	    return 0;
	}
    }
    my $t = $w->Toplevel(-title => "Manpage $man($mansec)");
    my $font_size = $w->base_font_size;
    my $more = $t->Scrolled("More",
			    -font => "Courier $font_size",
			    -scrollbars => $Tk::platform eq 'MSWin32' ? 'e' : 'w',
			   )->pack(-fill => "both", -expand => 1);
    $more->tagConfigure("bold", -font => "Courier $font_size bold");
    my $menu = $more->menu;
    $t->configure(-menu => $menu);
    local $SIG{PIPE} = "IGNORE";
    my $can_langinfo = $] >= 5.008 && eval { require I18N::Langinfo; 1 };
    local $ENV{LANG} = $ENV{LANG};
    if (!$can_langinfo) {
	$ENV{LANG} = "C";
    }
    open(MAN, $man_exe . (defined $mansec ? " $mansec" : "") . " $man |")
	or die $!;
    if ($can_langinfo) {
	my $codeset = I18N::Langinfo::langinfo(I18N::Langinfo::CODESET());
	eval qq{ binmode MAN, q{:encoding($codeset)} };
	warn $@ if $@;
    }
    if (eof MAN) {
	$more->insert("end", "No entry for for $man" . (defined $mansec ? " in section $mansec of" : "") . " the manual");
    } else {
	while(<MAN>) {
	    chomp;
	    (my $line = $_) =~ s/.\cH//g;
	    my @bold;
	    while (/(.*?)((?:(.)(\cH\3)+)+)/g) {
		my($pre, $bm) = ($1, $2);
		$pre =~ s/.\cH//g;
		$bm  =~ s/.\cH//g;
		push @bold, length $pre, length $bm;
	    }
	    if (@bold) {
		my $is_bold = 0;
		foreach my $length (@bold) {
		    if ($length > 0) {
			(my($s), $line) = $line =~ /^(.{$length})(.*)/;
			$more->insert("end", $s, $is_bold ? "bold" : ());
		    }
		    $is_bold = 1 - $is_bold;
		}
		$more->insert("end", "$line\n");
	    } else {
		$more->insert("end", "$line\n");
	    }
	}
    }
    close MAN;
    1;
}

sub EnterLink {
    my $w = shift;
    $w->configure(-cursor=>'hand2');
}

sub LeaveLink {
    my $w = shift;
    $w->configure(-cursor=>undef);
}

sub SearchFullText {
    my $w = shift;
    unless (defined $IDX && $IDX->IsWidget) {
	require Tk::Pod::Search; #
	$IDX = $w->Toplevel(-title=>'Perl Library Full Text Search');
	$IDX->transient($w);

	my $current_path;
	my $tree_sw = $w->parent->Subwidget("tree");
	if ($tree_sw) {
	    $current_path = $tree_sw->GetCurrentPodPath;
	}

	$IDX->PodSearch(
			-command =>
			sub {
			    my($pod, %args) = @_;
			    $w->configure('-file' => $pod);
			    $w->focus;
			    my $more = $w->Subwidget('more');
			    $more->SearchText
				(-direction => 'Next',
				 -quiet => 1,
				 -searchterm => $args{-searchterm},
				 -onlymatch => 1,
				);
			},
			-currentpath => $current_path,
		       )->pack(-fill=>'both',-expand=>'both');
	# XXX A very rough solution:
	$IDX->Button(-text => "Rebuild search index",
		     -command => sub {
		      my $installscriptdir = $Config{'installscript'};
		      my $perlindex = 'perlindex';
		      if (-d $installscriptdir)
		       {
			$perlindex = "$installscriptdir/perlindex";
			if (!-f $perlindex)
			 {
			  $w->_error_dialog("perlindex was expected in the path '$perlindex', but not found. Cannot build search index.");
			  return;
			 }
		       }
		      my $pw_bg_msg = "The next dialog will ask for the root password. The search index building will happen in background.";
		      if (!is_in_path("gksu"))
		       {
			if (!is_in_path("xsu"))
			 {
			  $w->_error_dialog("gksu or xsu needed to start perlindex");
			  return;
			 }
			$w->_warn_dialog($pw_bg_msg);
			if (fork == 0)
		         {
			  system('xsu',
				 '--command', "$perlindex -index",
				 '--username', 'root',
				 '--title' => 'Rebuild search index',
				 '--set-display' => $w->screen,
				);
			  CORE::exit(0);
			 }
		       }
		      else
		       {
			$w->_warn_dialog($pw_bg_msg);
			if (fork == 0)
			 {
			  system('gksu',
				 '--user', 'root',
				 #'--description', 'Rebuild search index',
				 "perlindex -index",
				);
			  CORE::exit(0);
			 }
		       }
		     }
		    )->pack(-fill => 'x');
	$IDX->Button(-text => "Close",
		     -command => sub { $IDX->destroy },
		    )->pack(-fill => 'x');
    }
    $IDX->deiconify;
    $IDX->raise;
    $IDX->bind('<Escape>' => [$IDX, 'destroy']);
    (($IDX->children)[0])->focus;
}

sub _need_File_Temp {
    my $w = shift;
    if (!eval { require File::Temp; 1 }) {
	$w->_die_dialog("The perl module 'File::Temp' is missing");
    }
}

sub Print {
    my $w = shift;

    my($text, $path);
    $path = $w->cget(-path);
    if (defined $path) {
	if (!-r $path) {
	    $w->_die_dialog("Cannot find file `$path`");
	}
    } else {
	$text = $w->cget("-text");
	$w->_need_File_Temp;
	my($fh,$fname) = File::Temp::tempfile(UNLINK => 1,
					      SUFFIX => "_tkpod.pod");
	print $fh $text;
	close $fh;
	$path = $fname;
    }

    if ($ENV{'TKPODPRINT'}) {
	my @cmd = _substitute_cmd($ENV{'TKPODPRINT'}, $path);
	DEBUG and warn "Running @cmd\n";
	system @cmd;
	return;
    } elsif ($^O =~ m/Win32/) {
	return $w->Print_MSWin($path);
    }
    # otherwise fall thru...

    my $success = $w->_print_pod_unix($path);

    if (!$success) {
	$w->_error_dialog("Can't print on your system.\nEither pod2man, groff,\ngv or ghostview are missing.");
    }
}

sub _print_pod_unix {
    my($w, $path) = @_;
    if (is_in_path("pod2man") && is_in_path("groff")) {
	my $pod2ps_pipe = "pod2man $path | groff -man -Tps";

	if ($^O eq 'darwin') {
	    my $cmd = "$pod2ps_pipe | /usr/bin/open -a Preview -f";
	    system($cmd) == 0
		or $w->_die_dialog("Error while executing <$cmd>. Status code is $?");
	    return 1;
	}

	# XXX maybe determine user's environment (GNOME vs. KDE vs. plain X11)?
	my $gv = is_in_path("gv")
	      || is_in_path("ghostview")
	      || is_in_path("ggv")         # newer versions seem to work
	      || is_in_path("kghostview");
	if ($gv) {
	    $w->_need_File_Temp;

	    my($fh,$fname) = File::Temp::tempfile(SUFFIX => "_tkpod.ps");
	    system("$pod2ps_pipe > $fname");
	    push @tempfiles, $fname;
	    my $pid = fork;
	    if (!defined $pid) {
		die "Can't fork: $!";
	    }
	    if ($pid == 0) {
		exec($gv, $fname);
		warn "Exec of $gv $fname failed: $!";
		CORE::exit(1);
	    }
	    push @gv_pids, $pid;
	    return 1;
	}
    }
    return 0;
}


sub _substitute_cmd {
    my($cmd, $path) = @_;
    my @cmd;
    if ($cmd =~ /%s/) {
	($cmd[0] = $cmd) =~ s/%s/$path/g;
    } else {
	@cmd = ($cmd, $path);
    }
    @cmd;
}

sub Print_MSWin {
  my($self, $path) = @_;
  my $is_old;
  $is_old = 1  if
   defined(&Win32::GetOSVersion) and
   eval {require Win32; 1} and
   defined(&Win32::GetOSName) and
    (Win32::GetOSName() eq 'Win32s'  or   Win32::GetOSName() eq 'Win95');
  require POSIX; # XXX should be probably replaced by File::Temp, but I have no Win machine to test...

  my $temp = POSIX::tmpnam(); # XXX it never gets deleted
  $temp =~ tr{/}{\\};
  $temp =~ s/\.$//;
  DEBUG and warn "Using $temp as the temp file for hardcopying\n";
  # XXX cleanup of temp file?

  if($is_old) { # so we can't assume that write.exe can handle RTF
    require Pod::Simple::Text;
    require Text::Wrap;
    local $Text::Wrap::columns = 65; # reasonable number, I think.
    $temp .= '.txt';
    Pod::Simple::Text->parse_from_file($path, $temp);
    system("notepad.exe", "/p", $temp);

  } else { # Assume that our write.exe should understand RTF
    require Pod::Simple::RTF;
    $temp .= '.rtf';
    Pod::Simple::RTF->parse_from_file($path, $temp);
    system("write.exe", "/p", "\"$temp\"");
  }

  return;
}

sub PrintHasDialog { $^O ne 'MSWin32' }

# Return $first and $last indices of the word under $index
sub _word_under_index {
    my($w, $index)= @_;
    my ($first,$last);
    $first = $w->search(qw/-backwards -regexp --/, '[^\w:]', $index, "$index linestart");
    $first = $w->index("$first + 1c") if $first;
    $first = $w->index("$index linestart") unless $first;
    $last  = $w->search(qw/-regexp --/, '[^\w:]', $index, "$index lineend");
    $last  = $w->index("$index lineend") unless $last;
    ($first, $last);
}

sub SelectToModule {
    my($w, $index)= @_;
    my ($first,$last) = $w->_word_under_index($index);
    if ($first && $last) {
	$w->tagRemove('sel','1.0',$first);
	$w->tagAdd('sel',$first,$last);
	$w->tagRemove('sel',$last,'end');
	$w->idletasks;
    }
}

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Add the file $file (with optional text index position $index) to the
# history.
sub history_add {
    my ($w,$what,$index) = @_;
    my($file, $text);
    if (ref $what eq 'HASH') {
	$file = $what->{file};
	$text = $what->{text};
    } else {
	$file = $what;
	$what = {file => $file};
    }
    if (defined $file) {
	unless (-f $file) {
	    $w->messageBox(-message => "Not a file '$file'. Can't add to history\n",
			   @{&HISTORY_DIALOG_ARGS});
	    return;
	}
    }
    my $hist = $w->privateData()->{history};
    my $hist_entry = Tk::Pod::Text::_HistoryEntry->create($what, $index, $w->{pod_title});
    $hist->[++$w->privateData()->{history_index}] = $hist_entry;
    splice @$hist, $w->privateData()->{history_index}+1;
    $w->history_view_update;
    $w->history_view_select;
    $w->_history_navigation_update;
    undef;
}

# Perform a "history back" operation, if possible. The current page is
# updated in the history.
sub history_back {
    my ($w) = @_;
    my $hist = $w->privateData()->{history};
    if (!@$hist) {
        $w->messageBox(-message => "History is empty",
		       @{&HISTORY_DIALOG_ARGS});
	return;
    }
    if ($w->privateData()->{history_index} <= 0) {
	$w->messageBox(-message => "Can't go back in history",
		       @{&HISTORY_DIALOG_ARGS});
	return;
    }

    $w->history_modify_entry;

    $hist->[--$w->privateData()->{history_index}];
}

# Perform a "history forward" operation, if possible. The current page is
# updated in the history.
sub history_forward {
    my ($w) = @_;
    my $hist = $w->privateData()->{history};
    if (!@$hist) {
        $w->messageBox(-message => "History is empty",
		       @{&HISTORY_DIALOG_ARGS});
	return;
    }
    if ($w->privateData()->{history_index} >= $#$hist) {
	$w->messageBox(-message => "Can't go forward in history",
		       @{&HISTORY_DIALOG_ARGS});
	return;
    }

    $w->history_modify_entry;

    $hist->[++$w->privateData()->{history_index}];
}

# Private method: update the pod view if called from a history back/forward
# operation. This method will set the specified _HistoryEntry object.
sub _history_update {
    my($w, $hist_entry) = @_;
    if ($hist_entry) {
	if (defined $hist_entry->file) {
	    if ($w->cget('-path') ne $hist_entry->file) {
		$w->privateData()->{'from_history'} = 1;
		$w->configure('-file' => $hist_entry->file);
		$w->privateData()->{'from_history'} = 0;
	    }
	} elsif (defined $hist_entry->text) {
	    $w->privateData()->{'from_history'} = 1;
	    $w->configure('-text' => $hist_entry->text);
	    $w->privateData()->{'from_history'} = 0;
	}
	$w->_history_navigation_update;
	$w->afterIdle(sub { $w->see($hist_entry->index) })
	    if $hist_entry->index;
    }
}

sub _history_navigation_update {
    my $w = shift;
    # XXX Be careful with the search pattern
    # if I decide to I18N Tk::Pod one day...
    my $m_history;
    if ($w->parent and $m_history = $w->parent->Subwidget("menubar")) {
	$m_history = $m_history->entrycget("History", "-menu");
	my $inx = $w->privateData()->{history_index};
	if ($inx == 0) {
	    $m_history->entryconfigure("Back", -state => "disabled");
	} else {
	    $m_history->entryconfigure("Back", -state => "normal");
	}
	if ($inx == $#{$w->privateData()->{history}}) {
	    $m_history->entryconfigure("Forward", -state => "disabled");
	} else {
	    $m_history->entryconfigure("Forward", -state => "normal");
	}
    }
}

# Move the history backward ($inc == -1) or forward ($inc == +1)
sub history_move {
    my($w, $inc) = @_;
    my $hist_entry = ($inc == -1 ? $w->history_back : $w->history_forward);
    $w->_history_update($hist_entry);
    $w->history_view_select;
}

# Set the history to the given index $inx.
sub history_set {
    my($w, $inx) = @_;
    if ($inx >= 0 && $inx <= $#{$w->privateData()->{history}}) {
	$w->history_modify_entry;
	$w->privateData()->{history_index} = $inx;
	$w->_history_update($w->privateData()->{history}->[$inx]);
    }
}

# Modify the index (position) information of the current history entry.
sub history_modify_entry {
    my $w = shift;
    if ($w->privateData()->{'history_index'} >= 0) {
	my $entry = $w->privateData()->{'history'}->[$w->privateData()->{'history_index'}];
	$entry->index($w->index('@0,0'));
    }
}

# Modify the pod title of the current history entry.
sub history_modify_current_title {
    my $w = shift;
    my $pod_title = $w->{pod_title};
    if (defined $pod_title) {
	my $history_index = $w->privateData()->{'history_index'};
	if ($history_index >= 0) {
	    my $entry = $w->privateData()->{'history'}->[$history_index];
	    $entry->pod_title($pod_title);
	    $w->history_view_update;
	    $w->history_view_select;
	}
    }
}

# Create a new history view toplevel or reuse an old one.
sub history_view {
    my $w = shift;
    my $t = $w->privateData()->{'history_view_toplevel'};
    if (!$t || !Tk::Exists($t)) {
	$t = $w->Toplevel(-title => 'History');
	$t->transient($w);
	$w->privateData()->{'history_view_toplevel'} = $t;
	my $lb = $t->Scrolled("Listbox", -scrollbars => 'oso'.($Tk::platform eq 'MSWin32'?'e':'w'))->pack(-fill => "both", '-expand' => 1);
	$t->Advertise(Lb => $lb);
	$lb->bind("<1>" => sub {
		      my $lb = shift;
		      my $y = $lb->XEvent->y;
		      $w->history_set($lb->nearest($y));
		  });
	$lb->bind("<Return>" => sub {
		      my $lb = shift;
		      my $sel = $lb->curselection;
		      return if !defined $sel;
		      $w->history_set($sel);
		  });
	$t->Button(-text => "Close",
		   -command => sub { $t->destroy },
		  )->pack(-fill => 'x');
    }
    $t->deiconify;
    $t->raise;
    $w->history_view_update;
    $w->history_view_select;
}

# Re-fill the history view with the current history array.
sub history_view_update {
    my $w = shift;
    my $t = $w->privateData()->{'history_view_toplevel'};
    if ($t && Tk::Exists($t)) {
	my $lb = $t->Subwidget('Lb');
	$lb->delete(0, "end");
	foreach my $histentry (@{$w->privateData()->{'history'}}) {
	    $lb->insert("end", $histentry->get_label);
	}
    }
}

# Move the history view selection to the current selected history entry.
sub history_view_select {
    my $w = shift;
    my $t = $w->privateData()->{'history_view_toplevel'};
    if ($t && Tk::Exists($t)) {
	my $lb = $t->Subwidget('Lb');
	$lb->selectionClear(0, "end");
	$lb->selectionSet($w->privateData()->{history_index});
    }
}

sub PostPopupMenu {
    my($w, $p_scr, $X, $Y) = @_;
    $w->{MenuX} = $X;
    $w->{MenuY} = $Y;
    $p_scr->PostPopupMenu($X, $Y);
}

sub OpenPodBySelection {
    my($w) = @_;
    my $sel;
    Tk::catch {
	$sel = $w->SelectionGet('-selection' => ($Tk::platform eq 'MSWin32'
						 ? "CLIPBOARD"
						 : "PRIMARY"));
    };
    $sel =~ s{\s}{}g; # no whitespace in Pod names possible
    $w->configure(-file => $sel);
}

sub _die_dialog {
    shift->_error_dialog(@_);
    die;
}

sub _error_dialog {
    my($w, $message) = @_;
    $w->messageBox(
      -title   => "Tk::Pod Error",
      -message => $message,
      -icon => 'error',
    );
}

sub _warn_dialog {
    my($w, $message) = @_;
    $w->messageBox(
      -title   => "Tk::Pod Warning",
      -message => $message,
      -icon => 'warning',
    );
}

sub cleanup_tempfiles {
    if (@tempfiles) {
	# first get rid of all possible zombies
	# before we can check with kill 0 => ...
	require POSIX;
	if (defined &POSIX::WNOHANG) { # defined everywhere?
	    while (waitpid(-1, &POSIX::WNOHANG) > 0) { }
	}

	my $gv_running;
	for my $pid (@gv_pids) {
	    if (kill 0 => $pid) {
		$gv_running = 1;
		last;
	    }
	}

	if ($gv_running) {
	    warn "A ghostscript (or equivalent) process is still running, won't delete temporary files: @tempfiles\n";
	} else {
	    for my $temp (@tempfiles) {
		unlink $temp;
	    }
	    @tempfiles = ();
	}
    }
}

END {
    cleanup_tempfiles();
}

1;

__END__

=head1 NAME

Tk::Pod::Text - Pod browser widget

=head1 SYNOPSIS

    use Tk::Pod::Text;

    $pod = $parent->Scrolled("PodText",
			     -file	 => $file,
			     -scrollbars => "osoe",
		            );

    $file = $pod->cget('-path');   # ?? the name path is confusing :-(

=cut

# also works with L<show|man/sec>. Therefore it stays undocumented :-)

#    $pod->Link(manual/section)	# as L<manual/section> see perlpod


=head1 DESCRIPTION

B<Tk::Pod::Text> is a readonly text widget that can display Pod
documentation.

=head1 OPTIONS

=over

=item -file

The named (pod) file to be displayed.

=item -path

Return the expanded path of the currently displayed Pod. Useable only
with the C<cget> method.

=item -poddone

A callback to be called if parsing and displaying of the Pod is done.

=item -wrap

Set the wrap mode. Default is C<word>.

=item -scrollbars

The position of the scrollbars, see also L<Tk::Scrolled>. By default,
the vertical scrollbar is on the right on Windows systems and on the
left on X11 systems.

Note that it is not necessary and usually will do the wrong thing if
you put a C<Tk::Pod::Text> widget into a C<Scrolled> component.

=back

Other options are propagated to the embedded L<Tk::More> widget.

=head1 ENVIRONMENT

=over

=item TKPODDEBUG

Turn debugging mode on if set to a true value.

=item TKPODPRINT

Use the specified program for printing the current pod. If the string
contains a C<%s>, then filename substitution is used, otherwise the
filename of the Pod document is appended to the value of
C<TKPODPRINT>. Here is a silly example to send the Pod to a web browser:

    env TKPODPRINT="pod2html %s > %s.html; galeon %s.html" tkpod ...

=item TKPODEDITOR

Use the specified program for editing the current pod. If
C<TKPODEDITOR> is not specified then the first defined value of
C<XEDITOR>, C<VISUAL>, or C<EDITOR> is used on Unix. As a last
fallback, C<ptked> or C<vi> are used, depending on platform and
existance of a terminal.

=item TKPODMANVIEWER

Use the specified program as the manpage viewer. The manpage viewer
should accept a manpage URL (C<man://>I<manpage>(I<section>)).
Alternatively the special viewer "internal" may be used. As fallback,
the default GNOME and/or KDE manpage viewer will be called.

=back

=head1 SEE ALSO

L<Tk::More|Tk::More>
L<Tk::Pod|Tk::Pod>
L<Tk::Pod::SimpleBridge|Tk::Pod::SimpleBridge>
L<Tk::Pod::Styles|Tk::Pod::Styles>
L<Tk::Pod::Search|Tk::Pod::Search>
L<Tk::Pod::Search_db|Tk::Pod::Search_db>
L<perlpod|perlpod>
L<tkpod|tkpod>
L<perlindex|perlindex>


=head1 KNOWN BUGS

See L<TODO> file of Tk-Pod distribution

=encoding utf-8

=head1 POD TO VERIFY B<PodText> WIDGET

For B<PodText> see L<Tk::Pod::Text>.

A C<fixed width> font.

Text in I<slant italics>.

A <=for> paragraph is hidden between here

=for refcard  this should not be visisble.

and there.

A file: F</usr/local/bin/perl>.  A variable $a without markup.

S<boofar> is in SE<lt>E<gt>.

Indexed items are not supported in Tk::Pod. X<Index Test>

Zero-Z<>effect formatting.

German umlauts:

=over 4

=item auml: E<auml> ä,

=item Auml: E<Auml> Ä,

=item ouml: E<ouml> ö,

=item Ouml: E<Ouml> Ö,

=item Uuml: E<uuml> ü,

=item Uuml: E<Uuml> Ü,

=item sz: E<szlig> ß.

=back

Unicode outside Latin1 range: E<0x20ac> (euro sign).

Pod with umlaut: L<ExtUtils::MakeMaker>.

Details:  L<perlpod> or perl, perlfunc.

External links: L<http://www.cpan.org> (URL), L<< URL with link text|http://www.cpan.org >>, L<perl> (man page), L<Berliner Fernsehturm|geo:52.520685,13.409461> (geo: URL)

Links to local sections: L<a section (SYNOPSIS)|/SYNOPSIS>, L<an item
(-file, currently wrong)|/-file>, L<a working item (auml)|/auml>.

Links to external sections: L<a section (DESCRIPTION in
perl.pod)|perl/DESCRIPTION>, L<an item (Uncuddled elses in
perlstyle.pod)|perlstyle/Uncuddled elses>.

Here some code in a as is paragraph

    use Tk;
    my $mw = MainWindow->new;
    ...
    MainLoop
    __END__


Fonts: C<fixed>, B<bold>, I<italics>, normal, or file
F</path/to/a/file>

Mixed Fonts: B<C<bold-fixed>>, B<I<bold-italics>>

Non-breakable text: S<The quick brown fox jumps over the lazy fox.>

Modern Pod constructs (multiple E<lt>E<gt>): I<< italic >>, C<< fixed
with embedded < and > >>.

Itemize with numbers:

=over

=item 1.

First

=item 2.

Second

=item 3.

Thirs

=back

Itemize with bullets:

=over

=item *

First

=item *

Second

=item *

Thirs

=back

=head1 TESTING HEAD1

=head2 TESTING HEAD2

=head3 TESTING HEAD3

=head4 TESTING HEAD4

=begin a_format_which_does_not_exist

This section should be invisible (=begin and =end).

=end a_format_which_does_not_exist

Other Pod docu: Tk::Font, Tk::BrowseEntry (not underlined, but
double-clickable in Tk::Pod)

=head1 AUTHOR

Nick Ing-Simmons <F<nick@ni-s.u-net.com>>

Current maintainer is Slaven ReziE<0x107> <F<slaven@rezic.de>>.

Copyright (c) 1998 Nick Ing-Simmons.  All rights reserved.  This program
is free software; you can redistribute it and/or modify it under the same
terms as Perl itself.

=cut

# Local Variables:
# mode: cperl
# cperl-indent-level: 4
# End: