This file is indexed.

/usr/share/pyshared/pydb/gdb.py is in pydb 1.26-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
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
"""Handles gdb-like command processing.
(See also pydb.doc for documentation.)
$Id: gdb.py.in,v 1.174 2009/03/31 19:52:58 rockyb Exp $"""
# -*- coding: utf-8 -*-
#   Copyright (C) 2007, 2008, 2009 Rocky Bernstein (rocky@gnu.org)
#
#    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; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
#    02110-1301 USA.

_debugger_name = 'pydb'

# The name of the debugger we are currently going by.
_version = '1.26'

import atexit, inspect, linecache, os, pprint, pydoc, shlex
import bdb, dis, disassemble, re, subcmd, sys, types


import bytecode, pydbcmd, pydbbdb
import signal
import sighandler
from complete import *

## from connection import ConnectionServerFactory, ConnectionClientFactory, ConnectionFailed
from bdb         import BdbQuit
from display     import Display, DisplayNode
from fns         import *
from info        import *
from set         import *
from show        import *

from pydbcmd import Cmd
from pydbbdb import Bdb

from threadinfo import *

class Restart(Exception):
    """Causes a debugger to be restarted for the debugged Python program."""
    pass

class Gdb(Bdb, Cmd, SubcmdInfo, SubcmdSet, SubcmdShow):
    """A debugger class for Python that resembles the gdb (GNU debugger)
    command set.

    Parameter completekey specifies the what to use for command completion.
    pass None if no command completion is desired.

    Parameters stdin and stdout specify where debugger input and output
    are to come from.
    
    Parameter siglist gives a list of signals to intercept and ignore.
    None means the default set. If you want *no* signals, use [].
    """

    def __init__(self, completekey='tab', stdin=None, stdout=None,
                 siglist=None):
        pydbbdb.Bdb.__init__(self)
        pydbcmd.Cmd.__init__(self, completekey, stdin, stdout)

        self._program_sys_argv    = []   # sys.argv after options are stripped
        self._re_linetrace_delay  = re.compile(r'\s*linetrace\s+delay')
        self._wait_for_mainpyfile = False

        # set up signal handling
        self.sigmgr          = sighandler.SignalManager(self,
                                                        ignore_list=siglist)
        self._reset_handler  = None

        self.__init_info()   # Initialize 'info' subcommands
        self.__init_set()    # Initialize 'set' subcommands
        self.__init_show()   # Initialize 'show' subcommands

        self.all_completions = lambda arg, left=True: \
                               all_completions(self, arg, left)
        self.autoeval        = True
        self.basename        = False
        self.connection      = None   # For out-of-process communication
        self.currentbp       = None   # for "info program"
        self.cur_frame       = None   # current stack frame
        self.dbg_pydb        = False  # Debug the debugger?
        self.def_trace       = False  # Show/stop at method create statements?
        self.debug_signal    = None   # The signal used by 'attach'
        self.display         = Display()
        self.fntrace         = False  # Tracing functions/methods
        self.gdb_dialect     = True   # Controls how stack is shown
        self.field_BdbQuit   = False  # does dispatcher field BdbQuit?

        # A list of the commands for which the first argument can be a
        # Python object. This is used by subcommand completions.
        self.first_can_be_obj = [
            "disassemble", "examine", "help", "p", "pp", "pydoc", "x",
            "whatis"
            ]
        
        self.is_in_dbg       = is_in_gdb
        self.lastcmd         = ''     # last debugger command run
        self.linetrace       = False
        self.linetrace_delay = 0
        self.listsize        = 10

        # main_dirname is the directory where the script resides;
        # "import" statments are relative to this location.

        self.main_dirname    = os.curdir
        self.mainpyfile      = ''
        self.maxargstrsize   = 100     # max length to show of parameter string
        self.moduletodebug   = ""
        self.noninteractive  = False   # Controls whether to prompt on
                                       # potentially dangerous commands.
        self.originalpath    = sys.path[:]
        self.orig_stdin      = self.stdin
        self.orig_stdout     = self.stdout
        self.running         = False
        self.search_path     = sys.path  # source name search path
        self.sigcheck        = True
        self.stop_reason     = None    # Why are we in the debugger?
        self._sys_argv       = []      # exec sys.argv, e.g. may include pydb
        self.set_history_length   = None
        self.stepping        = False   # used in thread debugging


        self.target          = 'local' # local connections by default
        self.target_addr     = ''      # target address used by 'attach'
        self.width           = 80      # Assume a printed line is this wide

        # self.break_anywhere, self.set_continue and
        # self.trace_dispatch are changed depending on the value of
        # 'set sigcheck'.  We may "decorate", in the design pattern
        # sense, the routines from bdb, so we need to save them.
        self.break_anywhere_old  = self.break_anywhere
        self.set_continue_old    = self.set_continue
        self.trace_dispatch_old  = self.trace_dispatch

        ## FIXME: for now we'll turn on signal trace dispatching
        self.break_anywhere  = self.break_anywhere_gdb
        self.set_continue    = self.set_continue_gdb
        self.trace_dispatch  = self.trace_dispatch_gdb

        # associates a command list to breakpoint numbers
        self.commands = {}

        # for each bp num, tells if the prompt must be disp. after
        # execing the cmd list
        self.commands_doprompt = {}

        # for each bp num, tells if the stack trace must be disp. after
        # execing the cmd list
        self.commands_silent = {}

        # True while in the process of defining a command list
        self.commands_defining = False

        # The breakpoint number for which we are defining a list
        self.commands_bnum = None #

        # list of all the commands making the program
        # resume execution.

        self.commands_resuming = ['do_continue', 'do_jump',  'do_next',
                                  'do_quit',     'do_return',
                                  'do_step']

        self.do_L = self.info_breakpoints

        # Try to load readline if it exists
        try:
            import readline
            import rlcompleter
            self.readline  = readline
            self.completer = rlcompleter.Completer(sys._getframe().f_locals)
            self.hist_last = 0
            self.hist_save = False
            self.set_history_length = readline.set_history_length
            # Set history length using gdb's rule.
            try:
                history_length = int(os.environ['HISTSIZE'])
            except:
                history_length = 256
            self.set_history_length(history_length)

            # An application like ipython may have its own
            # history set up beforehand, clear that so we don't back up
            # into that. Note that ipython saves and restores its own
            # history.
            if hasattr(readline, "clear_history"):
                readline.clear_history()

            # Read history file and set up to write history file when we
            # exit.
            global _debugger_name
            self.histfile = os.path.join(os.environ["HOME"],
                                         ".%shist" % _debugger_name)
            try:
                readline.read_history_file(self.histfile)
            except IOError:
                pass
            atexit.register(self.write_history_file)
            self.do_complete = self.__do_complete

        except ImportError:
            self.histfile = None
            return
        return

    def break_anywhere_gdb(self, frame):
        """Decorate bdb break_anywhere to consider the sigcheck and
        linetrace flags."""
        if self.sigcheck or self.linetrace or self.fntrace: return True
        return self.break_anywhere(frame)

    ### FIXME: trace_dispatch could be a performance bottleneck. If
    ### so, consider reassigning the routine when don't have any
    ### signals registered.
            
    def trace_dispatch_gdb(self, frame, event, arg):
        """Check to see if the signal handler's we are interested have
        changed. If so we'll intercept them. """
        if (not hasattr(self, 'thread_name') 
            or self.thread_name == 'MainThread'):
            self.sigmgr.check_and_adjust_sighandlers()

        # The below variable will be used to scan down frames to determine
        # if trace_dispatch has been called. We key on the variable
        # name, method name, type of variable and even the value.

        breadcrumb = is_in_gdb_dispatch

        try:
            return self.trace_dispatch_old(frame, event, arg)
        except BdbQuit:
            if self.field_BdbQuit:
                # If we have one thread (and know that this this is the case),
                # then we can use sys.exit(). Otherwise kill is the
                # only way to leave.
                if hasattr(sys, '_current_frames'):
                    if len(sys._current_frames()) == 1:
                        sys.exit()
                if self.noninteractive:
                    arg='unconditionally'
                else:
                    arg=''
                self.do_kill('')
                return False
            else:
                raise BdbQuit

    def __adjust_frame(self, pos, absolute_pos):
        """Adjust stack frame by pos positions. If absolute_pos then
        pos is an absolute number. Otherwise it is a relative number.

        If self.gdb_dialect is True, the 0 position is the newest
        entry and doesn't match Python's indexing. Otherwise it does.

        A negative number indexes from the other end."""
        if not self.curframe:
            self.msg("No stack.")
            return

        # Below we remove any negativity. At the end, pos will be
        # the new value of self.curindex.
        if absolute_pos:
            if self.gdb_dialect:
                if pos >= 0:
                    pos = len(self.stack)-pos-1
                else:
                    pos = -pos-1
            elif pos < 0:
                pos = len(self.stack)+pos
        else:
            pos += self.curindex

        if pos < 0:
            self.errmsg("Adjusting would put us beyond the oldest frame")
            return
        elif pos >= len(self.stack):
            self.errmsg("Adjusting would put us beyond the newest frame")
            return

        self.curindex = pos
        self.curframe = self.stack[self.curindex][0]
        self.print_location()
        self.lineno = None

    def __do_complete(self, arg):
        """Print a list of command names that can start with the
        supplied command prefix. If there is no completion nothing
        is printed."""
        completions = self.all_completions(arg)
        if completions is None: return
        for complete in completions:  self.msg(complete)
        return

    def __init_info(self):
        """Initialize info subcommands. Note: instance variable name
        has to be infocmds ('info' + 'cmds') for subcommand completion
        to work."""
        self.infocmds=subcmd.Subcmd("info", self.help_info.__doc__)
        self.infocmds.add('args',           self.info_args)
        self.infocmds.add('breakpoints',    self.info_breakpoints)
        self.infocmds.add('display',        self.info_display)
        self.infocmds.add('handle',         self.sigmgr.info_signal, 1, False)
        self.infocmds.add('globals',        self.info_globals, 1, False)
        self.infocmds.add('line',           self.info_line)
        self.infocmds.add('locals',         self.info_locals,  1, False)
        self.infocmds.add('program',        self.info_program)
        self.infocmds.add('signal',         self.sigmgr.info_signal, 2, False)
        self.infocmds.add('source',         self.info_source, 2)

        if hasattr(sys, "_current_frames"):
            self.info_threads = lambda arg: info_thread_new(self, arg)
            doc               = info_thread_new.__doc__
        else:
            try:
                import threadframe
                sys._current_frames = threadframe.dict # Make it look like 2.5
                self.info_threads   = lambda arg: info_threadframe(self, arg)
                doc                 = info_threadframe.__doc__
                
            except:
                self.info_threads = lambda arg: info_thread_old(self, arg)
                doc               = info_thread_old.__doc__
        self.info_threads.__doc__ = doc

        self.infocmds.add('threads', self.info_threads, 2)
        ## self.infocmds.add('target',         self.info_target)
        return

    def __init_set(self):
        """Initialize set subcommands. Note: instance variable name
        has to be setcmds ('set' + 'cmds') for subcommand completion
        to work."""

        self.setcmds=subcmd.Subcmd("set",   self.help_set.__doc__)
        self.setcmds.add('annotate',        self.set_annotate, 2)
        self.setcmds.add('args',            self.set_args, 2)
        self.setcmds.add('autoeval',        self.set_autoeval, 2)
        self.setcmds.add('basename',        self.set_basename)
        self.setcmds.add('debug-pydb',      self.set_dbg_pydb, 2)
        self.setcmds.add('deftrace',        self.set_deftrace, 2)
        self.setcmds.add('flush',           self.set_flush)
        self.setcmds.add('fntrace',         self.set_fntrace, 2)
        ## self.setcmds.add('debug-signal',    self.set_debug_signal)
        self.setcmds.add('history',         self.set_history)
        self.setcmds.add('interactive',     self.set_interactive)
        self.setcmds.add('linetrace',       self.set_linetrace, 3)
        self.setcmds.add('listsize',        self.set_listsize,  3)
        self.setcmds.add('logging',         self.set_logging,   2)
        self.setcmds.add('maxargsize',      self.set_maxargsize, 2)
        self.setcmds.add('prompt',          self.set_prompt)
        self.setcmds.add('sigcheck',        self.set_sigcheck)
        ## self.setcmds.add('target-address',  self.set_target_address)
        self.setcmds.add('trace-commands',  self.set_cmdtrace)
        self.setcmds.add('warnoptions',     self.set_warnoptions, 2)
        self.setcmds.add('width',           self.set_width,  2)
        return

    def __init_show(self):
        """Initialize show subcommands. Note: instance variable name
        has to be setcmds ('set' + 'cmds') for subcommand completion
        to work."""
        self.showcmds=subcmd.Subcmd("show", self.help_show.__doc__)
        self.showcmds.add('args',           self.show_args)
        self.showcmds.add('annotate',       self.show_annotate, 2)
        self.showcmds.add('autoeval',       self.show_autoeval, 2)
        self.showcmds.add('basename',       self.show_basename)
        self.showcmds.add('debug-pydb',     self.show_dbg_pydb)
        ## self.showcmds.add('debug-signal',   self.show_debug_signal)
        self.showcmds.add('deftrace',       self.show_deftrace,    3)
        self.showcmds.add('commands',       self.show_commands,    2, False)
        self.showcmds.add('directories',    self.show_directories, 1)
        self.showcmds.add('fntrace',        self.show_fntrace,     2)
        self.showcmds.add('flush',          self.show_flush)
        self.showcmds.add('history',        self.show_history)
        self.showcmds.add('interactive',    self.show_interactive)
        self.showcmds.add('linetrace',      self.show_linetrace,   3)
        self.showcmds.add('listsize',       self.show_listsize,    3)
        self.showcmds.add('logging',        self.show_logging,     2)
        self.showcmds.add('maxargsize',     self.show_maxargsize,  2)
        self.showcmds.add('prompt',         self.show_prompt)
        self.showcmds.add('sigcheck',       self.show_sigcheck)
        ## self.showcmds.add('target-address', self.show_target_address)
        self.showcmds.add('trace-commands', self.show_cmdtrace,    1)
        self.showcmds.add('version',        self.show_version)
        self.showcmds.add('warnoptions',    self.show_warnoptions, 2)
        self.showcmds.add('width',          self.show_width, 2)

    # To be overridden in derived debuggers
    def defaultFile(self):
        """Produce a reasonable default."""
        filename = self.curframe.f_code.co_filename
        # Consider using is_exec_stmt(). I just don't understand
        # the conditions under which the below test is true.
        if filename == '<string>' and self.mainpyfile:
            filename = self.mainpyfile
        return filename

    def display_enable(self, arg, flag):
        # arg is list of display points
        for i in arg:
            i = self.get_an_int(i, 'index %r is not a number' % i)
            if i is not None:
                self.display.enable_disable(i, flag)
                pass
            pass
        return

    def lineinfo(self, identifier):
        failed = (None, None, None)
        # Input is identifier, may be in single quotes
        idstring = identifier.split("'")
        if len(idstring) == 1:
            # not in single quotes
            ident = idstring[0].strip()
        elif len(idstring) == 3:
            # quoted
            ident = idstring[1].strip()
        else:
            return failed
        if ident == '': return failed
        parts = ident.split('.')
        # Protection for derived debuggers
        if parts[0] == 'self':
            del parts[0]
            if len(parts) == 0:
                return failed
        # Best first guess at file to look at
        fname = self.defaultFile()
        if len(parts) == 1:
            item = parts[0]
        else:
            # More than one part.
            # First is module, second is method/class
            f = self.lookupmodule(parts[0])
            if f:
                fname = f
            item = parts[1]
        answer = find_function(item, fname)
        return answer or failed

    def forget(self):
        self.lineno = None
        self.stack = []
        self.curindex = 0
        self.curframe = None
        return

    def interaction(self, frame, tb):
        """Possibly goes into loop to read debugger commands."""
        do_loop = self.setup(frame, tb) != 1
        if do_loop:
            if frame or tb:
                self.print_location(print_line=self.linetrace or self.fntrace)
                self.display.display(self.curframe)
            if not self.noninteractive:
                try:
                    self.cmdloop()
                except KeyboardInterrupt:
                    self.do_quit(None)
        self.currentbp = None    # Can forget it now that we're moving on
        self.forget()
        if not do_loop:
            # Tell cmdloop to break out of its loop.
            return True
        return False

    def parse_list_cmd(self, arg):
        """Parses arguments for the "list" command and returns the tuple
        filename, start, last
        or sets these to None if there was some problem."""

        if not self.curframe:
            self.msg("No Python program loaded.")
            return (None, None, None)

        self.lastcmd = 'list'
        last = None
        filename = self.curframe.f_code.co_filename
        if arg:
            if arg == '-':
                first = max(1, self.lineno - 2*self.listsize - 1)
            elif arg == '.':
                first = max(1, 
                            inspect.getlineno(self.curframe) - self.listsize/2)
            else:
                args = arg.split()
                (modfunc, filename, first) = parse_filepos(self, args[0])
                if first == None and modfunc == None:
                    # error should have been shown previously
                    return (None, None, None)
                if len(args) == 1:
                    first = max(1, first - (self.listsize/2))
                elif len(args) == 2:
                    (modfunc, last_filename, last) = \
                               parse_filepos(self, args[1])
                    if filename != last_filename \
                       and filename is not None and last_filename is not None:
                        self.errmsg('filename in the range must be the same')
                        return (None, None, None)
                    if last < first:
                        i = self.get_an_int(args[1],
                                            ('2nd number (%s) is less than the'
                                            + ' 1st number %d, but it does not'
                                            + ' evaluate to an integer')
                                            % (args[1], first))
                        if i is None:
                            return (None, None, None)
                        # Assume last is a count rather than an end line number
                        last = first + last
                elif len(args) > 2:
                    self.errmsg('At most 2 arguments allowed. Saw: %d' %
                                len(args))
                    return (None, None, None)
        elif self.lineno is None or not self.running:
            first = max(1, inspect.getlineno(self.curframe) - self.listsize/2)
        else:
            first = self.lineno + 1
        if last is None:
            last = first + self.listsize - 1

        return (filename, first, last)

    def set_continue_gdb(self):
        """Like bdb's set_continue but we don't have the run fast
        option"""
        self.stopframe = self.botframe
        self.returnframe = None
        self.quitting = 0
        return

    def setup(self, frame, tb=None):
        """Initialization done before entering the debugger-command
        loop. In particular we set up the call stack used for local
        variable lookup and frame/up/down commands.

        We return True if we should NOT enter the debugger-command
        loop."""
        self.forget()
        if self.dbg_pydb:
            frame = inspect.currentframe()
        if frame or tb:
            self.stack, self.curindex = self.get_stack(frame, tb)
            self.curframe = self.stack[self.curindex][0]
        else:
            self.stack = self.curframe = self.botframe = None
        if self.execRcLines()==1: return True
        return False

    def setup_source(self, arg, showError=False):
        """Set up to read commands from a source file"""
        try:
            rcFile = open(os.path.join(arg))
        except IOError, (errno, strerror):
            if showError:
                self.errmsg("Error opening debugger command file %s: %s"
                            % (arg, strerror))
            pass
        else:
            for line in rcFile.readlines():
                self.rcLines.append(line)
            rcFile.close()
        return

    def show_commands(self, arg):
        """Show the history of commands you typed.
You can supply a command number to start with, or a `+' to start after
the previous command number shown. A negative number starts from the end."""
        try:
            import readline
            if self.histfile is not None:
                hist_max = readline.get_current_history_length()
                if len(arg) <= 1:
                    first=1
                    self.hist_last=hist_max
                else:
                    if arg[1] == '+':
                        first = self.hist_last+1
                        self.hist_last = min(hist_max,
                                             first + self.listsize)
                    else:
                        try:
                            center = self.get_int(arg[1],
                                                  cmdname="show commands")
                        except ValueError:
                            return
                        if center < 0: center = hist_max + center + 1
                        first = max(1, center - (self.listsize/2))
                        self.hist_last = min(hist_max,
                                             center + (self.listsize/2))
                i=first
                while i<=self.hist_last:
                    self.msg("%5d  %s" % (i, readline.get_history_item(i)))
                    i += 1
            else:
                self.errmsg("History mechanism turned off.")
        except ImportError:
            self.errmsg("Readline not available.")

    def show_history(self, args):
        """Generic command for showing command history parameters"""
        try:
            import readline
            if len(args) > 1 and args[1]:
                show_save = show_size = show_filename = False
                show_prefix = False
                if args[1] == 'filename':
                    show_filename = True
                elif args[1] == 'save':
                    show_save = True
                elif args[1] == 'size':
                    show_size = True
                else:
                    self.undefined_cmd("show history", args[1])
                    return
            else:
                show_save = show_size = show_filename = True
                show_prefix = True
            if show_filename:
                if show_prefix:
                    prefix='filename: '
                else:
                    prefix=''
                self.msg("""%sThe filename in which to record the command history is
"%s".""" % (prefix, self.histfile))
            if show_save:
                if show_prefix:
                    prefix='save: '
                else:
                    prefix=''
                self.msg("%sSaving of the history record on exit is %s"
                         % (prefix, show_onoff(self.hist_save)))
            if show_size:
                if show_prefix:
                    prefix='size: '
                else:
                    prefix=''
                self.msg("%sThe size of the command history is %d"
                         % (prefix, readline.get_history_length()))
        except ImportError:
            pass

    def show_listsize(self, args):
        "Show number of source lines the debugger will list by default"
        self.msg("Number of source lines %s will list by default is %d." \
                 % (_debugger_name, self.listsize))

    def show_prompt(self, args):
        "Show debugger's prompt"
        self.msg("""%s's prompt is "%s".""" %
                 (_debugger_name, self.prompt))
        return

    def show_version(self, args):
        """Show what version of the debugger this is"""
        global _version
        self.msg("""%s version %s.""" %
                 (_debugger_name, _version))
        return

    def write_history_file(self):
        """Write the command history file -- possibly."""
        if self.hist_save:
            try:
                import readline
                try:
                    readline.write_history_file(self.histfile)
                except IOError:
                    pass
            except ImportError:
                pass

    ###################################################################
    # Command definitions, called by cmdloop()
    # The argument is the remaining string on the command line
    # Return true to exit from the command loop
    ###################################################################

    def do_alias(self, arg):
        """alias [name [command [parameter parameter ...] ]]
Creates an alias called 'name' the executes 'command'.  The command
must *not* be enclosed in quotes.  Replaceable parameters are
indicated by %1, %2, and so on, while %* is replaced by all the
parameters.  If no command is given, the current alias for name
is shown. If no name is given, all aliases are listed.

Aliases may be nested and can contain anything that can be
legally typed at the debugger prompt.  Note!  You *can* override
internal debugger commands with aliases!  Those internal commands
are then hidden until the alias is removed.  Aliasing is recursively
applied to the first word of the command line; all other words
in the line are left alone.

Some useful aliases (especially when placed in the .pydbsrc file) are:

#Print instance variables (usage "pi classInst")
alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]

#Print instance variables in self
alias ps pi self
"""
        args = arg.split()
        if len(args) == 0:
            keys = self.aliases.keys()
            keys.sort()
            for alias in keys:
                self.msg("%s = %s" % (alias, self.aliases[alias]))
            return
        if args[0] in self.aliases and len(args) == 1:
            self.msg("%s = %s" % (args[0], self.aliases[args[0]]))
        else:
            self.aliases[args[0]] = ' '.join(args[1:])

    def do_break(self, arg, temporary = 0, thread_name=None):

        """b(reak) [[file:]lineno | function] [, condition]

With a line number argument, set a break there in the current file.
With a function name, set a break at first executable line of that
function.  Without argument, set a breakpoint at current location.  If
a second argument is present, it is a string specifying an expression
which must evaluate to true before the breakpoint is honored.

The line number may be prefixed with a filename and a colon,
to specify a breakpoint in another file (probably one that
hasn't been loaded yet).  The file is searched for on sys.path;
the .py suffix may be omitted."""
        if not self.curframe:
            self.msg("No stack.")
            return
        cond = None
        funcname = None
        if not arg:
            if self.lineno is None:
                lineno = max(1, inspect.getlineno(self.curframe))
            else:
                lineno = self.lineno + 1
            filename = self.curframe.f_code.co_filename
        else:
            # parse arguments; comma has lowest precedence
            # and cannot occur in filename
            filename = None
            lineno = None
            comma = arg.find(',')
            if comma > 0:
                # parse stuff after comma: "condition"
                cond = arg[comma+1:].lstrip()
                arg = arg[:comma].rstrip()
            (funcname, filename, lineno) = parse_filepos(self, arg)
            if lineno is None: return

        # FIXME This default setting doesn't match that used in
        # do_clear. Perhaps one is non-optimial.
        if not filename:
            filename = self.defaultFile()

        # Check for reasonable breakpoint
        line = checkline(self, filename, lineno)
        if line:
            # now set the break point
            # Python 2.3.5 takes 5 args rather than 6.
            # There is another way in configure to test for the version,
            # but this works too.
            try:
               err = self.set_break(filename, line, temporary, cond, funcname)
            except TypeError:
               err = self.set_break(filename, line, temporary, cond)

            if err: self.errmsg(err)
            else:
                bp = self.get_breaks(filename, line)[-1]
                if thread_name is None:
                    self.msg("Breakpoint %d set in file %s, line %d."
                             % (bp.number, self.filename(bp.file), bp.line))
                else:
                    bp.thread_name = thread_name
                    self.msg("Breakpoint %d set in file %s, line %d, thread %s."
                             % (bp.number, self.filename(bp.file), bp.line,
                                thread_name))

    do_b = do_break

    def do_cd(self, arg):
        """Set working directory to DIRECTORY for debugger and program
        being debugged. """
        if not arg:
            self.errmsg("Argument required (new working directory).")
        else:
            os.chdir(arg)
            return
        return

    def do_clear(self, arg):
        """cl(ear) {[file:]linenumber | function}

        Clear breakpoint at specified line or function.  Argument may
        be line number, function name, or '*' and an address.  If line
        number is specified, all breakpoints in that line are cleared.
        If function is specified, breakpoints at beginning of function
        are cleared.  If an address is specified, breakpoints at that
        address are cleared.

        With no argument, clears all breakpoints in the line that the
        selected frame is executing in.

        See also the 'delete' command which clears breakpoints by number.
        """

        if not self.curframe:
            self.msg("No frame selected.")
            return False
        if not arg:
            frame, lineno = self.stack[self.curindex]
            filename = self.canonic_filename(self.curframe)

        else:
            if ':' in arg:
                # Make sure it works for "clear C:\foo\bar.py:12"
                i = arg.rfind(':')
                filename = arg[:i]
                arg = arg[i+1:]
                try:
                    lineno = int(arg)
                except:
                    self.errmsg("Invalid line number (%s)" % arg)
                    return False
            else:
                (funcname, filename, lineno) = get_brkpt_lineno(self, arg)

            if lineno is None: return False

            # FIXME This default setting doesn't match that used in
            # do_break. Perhaps one is non-optimial.
            if filename is None:
                filename = self.canonic_filename(self.curframe)

        brkpts = self.clear_break(filename, lineno)

        if len(brkpts) > 0:
            if len(brkpts) == 1:
                self.msg("Deleted breakpoint %d" % brkpts[0])
            else:
                self.msg("Deleted breakpoints " +
                         ' '.join(map(lambda b: str(b), brkpts)))
                return False
            return False
        return False

    do_cl = do_clear

    def do_commands(self, arg):

        """Defines a list of commands associated to a breakpoint Those
        commands will be executed whenever the breakpoint causes the
        program to stop execution."""

        if not arg:
            bnum = len(bdb.Breakpoint.bpbynumber)-1
        else:
            try:
                bnum = self.get_pos_int(arg, min_value=0, default=None,
                                        cmdname="'commands'")
            except ValueError:
                return False
        if not (bnum < len(bdb.Breakpoint.bpbynumber)):
            self.errmsg('No breakpoint numbered %d.' % bnum)
            return False

        self.commands_bnum = bnum
        self.commands[bnum] = []
        self.commands_doprompt[bnum] = True
        self.commands_silent[bnum] = False

        self.commands_defining = True
        if self.setup(self.curframe) == 1:
            self.commands_defining = False
            return False

        prompt_back = self.prompt
        self.prompt = '>'
        self.msg("Type commands for when breakpoint %d is hit, one per line."
                 % bnum)
        self.msg('End with a line saying just "end".')

        self.cmdloop()
        self.commands_defining = False
        self.prompt = prompt_back
        return False

    def do_condition(self, arg):
        """condition bpnumber str_condition

        str_condition is a string specifying an expression which must
        evaluate to true before the breakpoint is honored.  If
        str_condition is absent, any existing condition is removed;
        i.e., the breakpoint is made unconditional."""

        args = arg.split(' ', 1)
        try:
            bpnum = self.get_pos_int(args[0].strip(), min_value=1,
                                     cmdname='condition')
        except ValueError:
            return
        except IndexError:
            self.errmsg("Breakpoint number required.")
        try:
            cond = args[1]
        except:
            cond = None
        try:
            bp = bdb.Breakpoint.bpbynumber[bpnum]
        except IndexError:
            self.errmsg("No breakpoint numbered %d." % bpnum)
            return False
        if bp:
            bp.cond = cond
            if not cond:
                self.msg('Breakpoint %d is now unconditional.' % bpnum)

    # Note: ddd only uses first line of docstring after the command name.
    # That is the part that starts Continue execution...
    # So make sure this is a complete sentence.
    def do_continue(self, arg):
        """c(ontinue) [[file:]lineno | function]

Continue execution; only stop when a breakpoint is encountered. If a
line position is given, continue until that line is reached. This is
exactly the same thing as setting a temporary breakpoint at that
position before running an (unconditional) continue."""
        if not self.is_running(): return
        if self.linetrace or self.fntrace:
            # linetracing is like stepping, but we just don't stop. If
            # we were to calling set_continue, it  *might* remove all
            # stopping if there were no breakpoints.
            self.step_ignore = -1
            self.set_step()
            self.stepping = True
        else:
            self.stepping = False

        if arg:
            (funcname, filename, lineno) = parse_filepos(self, arg)
            if lineno:
                self.do_tbreak(arg)

        # This has to be done after do_tbreak
        if not (self.linetrace or self.fntrace):
            self.set_continue()
            
        # Tell cmdloop to break out of its loop.
        return True

    do_c = do_continue

    def do_debug(self, arg):
        """debug code
        Enter a recursive debugger that steps through the code argument
        (which is an arbitrary expression or statement to be executed
        in the current environment)."""
        if not self.curframe:
            self.msg("No frame selected.")
            return
        sys.settrace(None)
        global_vars = self.curframe.f_globals
        local_vars = self.curframe.f_locals
        p = Gdb()
        p.prompt  = "(%s) " % self.prompt.strip()
        self.msg("ENTERING RECURSIVE DEBUGGER")

        # Inherit some values from current environemnt
        p.aliases         = self.aliases
        p.basename        = self.basename
        p.cmdtrace        = self.cmdtrace
        p.fntrace         = self.fntrace
        p.gdb_dialect     = self.gdb_dialect
        p.infocmds        = self.infocmds
        p.linetrace       = self.linetrace
        p.linetrace_delay = self.linetrace_delay
        p.listsize        = self.listsize
        p.noninteractive  = self.noninteractive
        for attr in ('thread_name', 'no_thread_do_break', 'nothread_do_tbreak',
                     'nothread_trace_dispatch', 'nothread_quit',
                     'desired_thread'):
            if hasattr(self, attr):
                setattr(p, attr, getattr(self, attr))

        # Some values that are different from the current environment
        # and different from the default initialization values.
        p.running         = True  # We *are* trying to run something
        p.step_ignore     = 1     # We need to skip one statement

        sys.call_tracing(p.run, (arg, global_vars, local_vars))
        self.msg("LEAVING RECURSIVE DEBUGGER")
        # sys.settrace() seems to mess up self.print_location
        # so print location first.
        self.print_location()
        sys.settrace(self.trace_dispatch)
        self.lastcmd = p.lastcmd
        return False

    def do_delete(self, arg):
        """delete [bpnumber [bpnumber...]]  - Delete some breakpoints.
        Arguments are breakpoint numbers with spaces in between.  To
        delete all breakpoints, give no argument.  those breakpoints.
        Without argument, clear all breaks (but first ask
        confirmation).

        See also the 'clear' command which clears breakpoints by
        line/file number.."""
        if not arg:
            if get_confirmation(self, 'Delete all breakpoints'):
                self.clear_all_breaks()
            return

        numberlist = arg.split()
        for arg in numberlist:
            try:
                i = self.get_pos_int(arg, min_value=1, default=None,
                                     cmdname='delete')
            except ValueError:
                continue

            if not (i < len(bdb.Breakpoint.bpbynumber)):
                self.errmsg('No breakpoint numbered %d.' % i)
                continue
            err = self.clear_bpbynumber(i)
            if err:
                self.errmsg(err)
            else:
                self.msg('Deleted breakpoint %d' % i)

    def do_directory(self, arg):

        """Add directory DIR to beginning of search path for source
files.  Forget cached info on source file locations and line
positions.  DIR can also be $cwd for the current working directory, or
$cdir for the directory in which the source file was compiled into
object code.  With no argument, reset the search path to $cdir:$cwd,
the default."""
        args = arg.split()
        if len(args) == 0:
            if get_confirmation(self,
                'Reinitialize source path to empty'):
                self.search_path=[]
            return
        else:
            # FIXME: Loop over arguments checking for directory?
            self.search_path.insert(0, args[0])

    def do_disable(self, arg):
        """disable [display] bpnumber [bpnumber ...]

        Disables the breakpoints given as a space separated list of bp
        numbers."""

        args = arg.split()
        if len(args) == 0:
            self.errmsg('No breakpoint number given.')
            return
        if args[0] == 'display':
            self.display_enable(args[1:], 0)
            return
        for i in args:
            try:
                i = int(i)
            except ValueError:
                self.msg('Breakpoint index %r is not a number.' % i)
                continue

            if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
                self.msg('No breakpoint numbered %d.' % i)
                continue

            bp = bdb.Breakpoint.bpbynumber[i]
            if bp:
                bp.disable()

    def do_disassemble(self, arg):
        """disassemble [obj-or-class] [[+|-]start-line [[+|-]end-line]]

With no argument, disassemble the current frame.  With a start-line
integer, the disassembly is narrowed to show lines starting at that
line number or later; with an end-line number, disassembly stops
when the next line would be greater than that or the end of the code
is hit. If start-line or end-line has a plus or minus prefix, then the
line number is relative to the current frame number.

With a class, method, function, code or string argument disassemble
that."""

        if arg:
            args = arg.split()
        else:
            args = []
        start_line = end_line = None
        relative_pos = False
        if len(args) > 0:
            if args[0] in ['+', '-']: 
                start_line = self.curframe.f_lineno
                relative_pos = True
            else:
                start_line = int(args[0])
                if args[0][0:1] in ['+', '-']: 
                    relative_pos = True
                    start_line += self.curframe.f_lineno
                    pass
                pass

            if len(args) == 2:
                try:
                    end_line = self.get_int(args[1], cmdname="disassemble")
                except ValueError:
                    return False
            elif len(args) > 2:
                self.errmsg("Expecting 1-2 line parameters, got %d" %
                            len(args))
                return False
            if not self.curframe:
                self.errmsg("No frame selected.")
                return False
            disassemble.disassemble(self, self.curframe.f_code,
                                    start_line=start_line,
                                    end_line=end_line,
                                    relative_pos=relative_pos)
            pass
        try:
            if len(args) > 1:
                try:
                    start_line = self.get_int(args[1],
                                              cmdname="disassemble")
                    if args[1][0:1] in ['+', '-']: 
                        relative_pos = True
                        start_line += self.curframe.f_lineno
                        pass
                    if len(args) == 3:
                        end_line = self.get_int(args[2],
                                                cmdname="disassemble")
                    elif len(args) > 3:
                        self.errmsg("Expecting 0-3 parameters, got %d" %
                                    len(args))
                        return False
                except ValueError:
                    return False
                pass
            
                if hasattr(self, 'curframe') and self.curframe:
                    obj=self.getval(args[0])
                else:
                    obj=eval(args[0])
                    pass
                disassemble.dis(self, obj,
                                start_line=start_line, end_line=end_line,
                                relative_pos=relative_pos)
        except NameError:
            self.errmsg("Object '%s' is not something we can disassemble"
                        % args[0])
        return False

    def do_display(self, arg):
        """display [format] EXP

        Print value of expression EXP each time the program stops.
        FMT may be used before EXP and may be one of 'c' for char,
        'x' for hex, 'o' for octal, 'f' for float or 's' for string.

        With no argument, display all currently requested auto-display
        expressions.  Use "undisplay" to cancel display requests previously
        made."""

        if not arg:
            # Display anything active
            self.display.display(self.curframe)
        else:
            # Set up a display
            arglist = arg.split()
            if len(arglist) == 2:
               format, variable = arglist
            else:
               format = ""
               variable = arglist[0]
            dp = DisplayNode(self.curframe, variable, format)
            res = dp.checkValid(self.curframe)
            self.msg(res)
        return False

    def do_down(self, arg):
        """d(own) [count]

        Move the current frame one level down in the stack trace
        (to a newer frame).

        If using gdb dialect up matches the gdb: 0 is the most recent
        frame.  Otherwise we match Python's stack: 0 is the oldest
        frame.  """

        try:
            count = self.get_int(arg, cmdname="down")
        except ValueError:
            return
        if self.gdb_dialect:
            count = -count
        self.__adjust_frame(pos=-count, absolute_pos=False)
        return False

    def do_enable(self, arg):
        """enable [display] bpnumber [bpnumber ...]]

        Enables the breakpoints given as a space separated list of bp
        numbers."""
        args = arg.split()
        if len(args) == 0:
            self.errmsg('No breakpoint number given')
            return

        if args[0] == 'display':
            self.display_enable(args[1:], True)
            return

        for i in args:
            i = self.get_an_int(i, 'Breakpoint index %r is not a number' % i)
            if i is None: continue

            if not (1 <= i < len(bdb.Breakpoint.bpbynumber)):
                self.errmsg('No breakpoint numbered %d.' % i)
                continue

            bp = bdb.Breakpoint.bpbynumber[i]
            if bp:
                bp.enable()

    def do_examine(self, arg):
        """examine expression - Print the expression, its value, type,
        and object attributes."""
        s = print_obj(arg, self.curframe)
        self.msg(s)

    do_x = do_examine

    def do_file(self, fname):
        """Use FILE as the Python program to be debugged.
It is compiled and becomes is the program executed when you use the `run'
command.  If no filename is given, this means to set things so there
is no Python file."""
        
        if fname == "":
           if self.mainpyfile == "":
               self.msg('No exec file now.\nNo symbol file now.')
               return
           else:
               # should confirm this per
               if get_confirmation(self, "Discard symbol table from '%s'"
                                   % self.mainpyfile):
                   # XXX how to clean up name space ??
                   self._program_sys_argv = None
                   self.mainpyfile = ''
        else:
            # XXX how to clean up name space ??
            if os.path.exists(fname):
                self.mainpyfile=fname
                self._program_sys_argv = [self.mainpyfile]
                self._runscript(self.mainpyfile)
                # Fake up curframe? 
                return self.quitting
            else:
                self.errmsg("file '%s' does not exist" % fname)
                return None
            pass
        pass

    def do_finish(self, arg):
        """finish

        Continue execution until the current function returns."""
        if not self.is_running(): return
        self.set_return(self.curframe)
        self.stepping = False
        if self.linetrace:
            self.stepping    = True
            self.step_ignore = -1
            self.stopframe   = None

        # Tell cmdloop to break out of its loop.
        return True

    def do_frame(self, arg):
        """frame [frame-number]

        Move the current frame to frame `frame-number' if specified,
        or the current frame, 0 if no frame number specified.

        A negative number indicates position from the other end.
        So 'frame -1' moves when gdb dialect is in effect moves
        to the oldest frame, and 'frame 0' moves to the newest frame."""

        if not self.stack:
            self.msg("Program has no stack frame set.")
            return False
        arg = arg.strip() or '0'
        arg = self.get_an_int(arg,
                              ("The 'frame' command requires a frame number."+
                               " Got: %s") % arg)
        if arg is None: return False

        i_stack = len(self.stack)
        if arg < -i_stack or arg > i_stack-1:
            self.errmsg('Frame number has to be in the range %d to %d' \
                  % (-i_stack, i_stack-1))
        else:
            self.__adjust_frame(pos=arg, absolute_pos=True)
        return False

    def do_handle(self, arg):
        """Specify how to handle a signal.
        
Args are signals and actions to apply to those signals.
recognized actions include "stop", "nostop", "print", "noprint",
"pass", "nopass", "ignore", or "noignore".

- Stop means reenter debugger if this signal happens (implies print and
  nopass).
- Print means print a message if this signal happens.
- Pass means let program see this signal; otherwise program doesn't know.
- Ignore is a synonym for nopass and noignore is a synonym for pass.
- Pass and Stop may not be combined. (This is different from gdb)
        """
        self.sigmgr.action(arg)

    def do_ignore(self,arg):
        """ignore bpnumber count

        Sets the ignore count for the given breakpoint number.  A
        breakpoint becomes active when the ignore count is zero.  When
        non-zero, the count is decremented each time the breakpoint is
        reached and the breakpoint is not disabled and any associated
        condition evaluates to true."""
        args = arg.split()

        bpnum = self.get_an_int(args[0],
                                ("ignore: bpnumber %s does not evaluate to an"
                                + " integer") % args[0], min_value=1)
        if bpnum is None: return False
        if not (0 <= bpnum < len(bdb.Breakpoint.bpbynumber)):
                self.errmsg('No breakpoint numbered %d.' % bpnum)
                return False

        if len(args) > 1:
            count = self.get_an_int(args[1],
                                    ("ignore: count %s does not evaluate to an"
                                    + " integer.") % args[0], min_value=0)
            if count is None: return False
        else:
            count = 0
            
        bp = bdb.Breakpoint.bpbynumber[bpnum]
        if bp:
            bp.ignore = count
            if count > 0:
                reply = 'Will ignore next '
                if count > 1:
                    reply = reply + '%d crossings' % count
                else:
                    reply = reply + '1 crossing'
                self.msg('%s of breakpoint %d.' % (reply, bpnum))
            else:
                self.msg('Will stop next time breakpoint %d is reached.' %
                         bpnum)
            return False
        return False

    def do_ipython(self, arg_str):
        """ipython [ipython-opt1 ipython-opt2 ...]

Run IPython as a command subshell. You need to have ipython installed
for this command to work. If no IPython options are given, the
following options are passed: 
   -noconfirm_exit -prompt_in1 'Pydbgr In [\#]: '

You can access debugger state via local variable "ipydb".
Debugger commands like are installed as IPython magic commands, e.g.
%list, %up, %where.
"""

        if not self.is_running():
            return False

        if arg_str:
            argv = arg_split(arg_str, posix=True)
        else:
            argv = ['-noconfirm_exit','-prompt_in1', 'Pydb In [\\#]: ']
            pass

        if self.curframe and self.curframe.f_locals:
            user_ns = self.curframe.f_locals
        else:
            user_ns = {}

        # IPython does it's own history thing.
        # Make sure it doesn't damage ours.
        if self.readline:
            try:
                self.write_history_file()
            except IOError:
                pass

        # ipython should be around - it was before.
        try:
            import IPython
        except ImportError:
            self.errmsg("IPython doesn't seem to be importable.")
            return False

        user_ns['ipydb'] = self
        ipshell = IPython.Shell.IPShellEmbed(argv=argv, user_ns=user_ns)
        user_ns['ipshell'] = ipshell

        # Give ipython and the user a way to get access to the debugger
        setattr(ipshell, 'ipydb', self)

        if hasattr(ipshell.IP, "magic_pydb"):
            # We get an infinite loop when doing recursive edits
            self.msg("Removing magic %pydb")
            delattr(ipshell.IP, "magic_pydb")
            pass
        
        # add IPython "magic" commands for all debugger comamnds and
        # aliases.  No doubt, this probably could be done in a
        # better way without "exec".  (Someone just needs to suggest
        # a way...)
        ip = IPython.ipapi.get()
        magic_fn_template="""
def ipy_%s(self, args):
   dbg = self.user_ns['ipydb']
   dbg.continue_running = dbg.do_%s(args)
   if dbg.continue_running: self.shell.exit()
   return
ip.expose_magic("%s", ipy_%s)
"""
        expose_magic_template = 'ip.expose_magic("%s", ipy_%s)'
        for name in self.get_cmds():
            exec magic_fn_template % ((name,) * 4)
            pass
            
        # And just when you thought we've forgotten about running
        # the shell...
        ipshell()

        # Restore our history if we can do so.
        if self.readline and self.histfile is not None:
            try:
                self.readline.read_history_file(self.histfile)
            except IOError:
                pass
            return False
        return self.continue_running
                
    def do_info(self, arg):

        """Generic command for showing things about the program being
        debugged. You can give unique prefix of the name of a subcommand to
        get info about just that subcommand."""

        if not arg:
            for subcommand in self.infocmds.list():
                # Some commands have lots of output.
                # they are excluded here because 'in_list' is false.
                if self.infocmds.subcmds[subcommand]['in_list']:
                    self.msg_nocr("%s: " % subcommand)
                    self.do_info(subcommand)
            return

        else:
            args = arg.split()
            self.infocmds.do(self, args[0], args)

    def do_jump(self, arg, cmdname='Jump'):
        """jump lineno

        Set the next line that will be executed."""

        if not self.is_running(): return False

        if self.curindex + 1 != len(self.stack):
            self.errmsg("You can only jump within the bottom frame")
            return False
        arg = self.get_an_int(str(arg),
                              "jump: a line number is required, got %s." %
                              arg)
        if arg is None: return False
        try:
            # Do the jump, fix up our copy of the stack, and display the
            # new position
            self.curframe.f_lineno = arg
            self.stack[self.curindex] = self.stack[self.curindex][0], arg
            self.print_location()
        except ValueError, e:
            self.errmsg('%s failed: %s' % (cmdname, e))
        return False

    def do_kill(self, arg):
        """kill [unconditionally]

Kill execution of program being debugged.

Equivalent of kill -KILL <pid> where <pid> is os.getpid(), the current
debugged process. This is an unmaskable signal. When all else fails, e.g. in
thread code, use this.

If 'unconditionally' is given, no questions are asked. Otherwise, if
we are in interactive mode, we'll prompt to make sure.
"""
        if len(arg) > 0 and 'unconditionally'.startswith(arg) or \
               get_confirmation(self, 'Really do a hard kill', True):
            os.kill(os.getpid(), signal.SIGKILL)
            return False # Possibly not reached
        pass

    def do_list(self, arg):
        """l(ist) [- | . | first [last or count]]

List source code. 

Without arguments, list LISTSIZE lines centered around the current
line or continue the previous listing. "list -" lists LISTSIZE lines
before a previous listing. "list ." means list centered around the current
frame pointer.

With one argument other than "-" or '.', list LISTSIZE lines centered
around the specified position.  With two arguments, list the given
range; if the second argument is less than the first, it is a count.
First and last can be either a function name, a line number or
file:line"""

        filename, first, last = self.parse_list_cmd(arg)
        if filename is None: return
        breaklist = self.get_file_breaks(filename)

        # Python 2.5 or greater has 3 arg getline which handles
        # eggs and zip files
        if 3 == linecache.getline.func_code.co_argcount:
            getline = lambda f, l: linecache.getline(f, l, 
                                                     self.curframe.f_globals)
        else:
            getline = lambda f, l: linecache.getline(f, l)
            pass

        # We now have range information. Do the listing.
        try:
            for lineno in range(first, last+1):
                line = getline(filename, lineno)
                if not line:
                    self.msg('[EOF]')
                    break
                else:
                    s = self._saferepr(lineno).rjust(3)
                    if len(s) < 4: s = s + ' '
                    if lineno in breaklist: s = s + 'B'
                    else: s = s + ' '
                    if lineno == inspect.getlineno(self.curframe) \
                       and filename == self.curframe.f_code.co_filename:
                        s = s + '->'
                    self.msg_nocr(s + '\t' + line)
                    self.lineno = lineno
        except KeyboardInterrupt:
            pass
        return False

    do_l = do_list

    def do_next(self, arg):
        """n(ext) [count]
Continue execution until the next line in the current function is reached or it returns.

With an integer argument, perform 'next' that many times."""
        if not self.is_running(): return
        try:
            # 0 means stop now or step 1, so we subtract 1.
            self.step_ignore = self.get_pos_int(arg, default=1,
                                                cmdname='next') - 1
        except ValueError:
            return False

        self.stepping = True  # Used in thread debugging
        self.set_next(self.curframe)
        # Tell cmdloop to break out of its loop.
        return True

    do_n = do_next

    def do_p(self, arg):
        """Print the value of the expression. Variables accessible are those of the
environment of the selected stack frame, plus globals. 

The expression may be preceded with /FMT where FMT is one of the
format letters 'c', 'x', 'o', 'f', or 's' for chr, hex, oct, 
float or str respectively.

If the length output string large, the first part of the value is
shown and ... indicates it has been truncated

See also `pp' and `examine' for commands which do more in the way of
formatting."""
        args = arg.split()
        if len(args) > 1 and '/' == args[0][0]:
            fmt = args[0]
            del args[0]
            arg = ' '.join(args)
        else:
            fmt = None
            pass
        try:
            val = self.getval(arg)
            if fmt:
                val = fns.printf(val, fmt)
                pass
            self.msg(self._saferepr(val))
        except:
            pass

    def do_pdef(self, arg):
        """pdef obj

Print the definition header for a callable object.
If the object is a class, print the constructor information.

See also pydoc."""
        args = arg.split()
        if len(args) != 1: return
        obj_name = args[0]
        try:
            obj = eval(arg, self.curframe.f_globals,
                             self.curframe.f_locals)
        except:
            return
        if not callable(obj):
            self.errmsg('Object %s is not callable.' % obj_name)
            return

        if inspect.isclass(obj):
            self.msg('Class constructor information:')
            obj = obj.__init__
        elif type(obj) is types.InstanceType:
            obj = obj.__call__
            pass

        output = print_argspec(obj, obj_name)
        if output is None:
            self.errmsg('No definition header found for %s' % obj_name)
        else:
            self.msg(output)
            pass
        return

    def do_pp(self, arg):
        """pp expression
        Pretty-print the value of the expression."""
        try:
            val = self.getval(arg)
            if type(val) == types.ListType:
                # Handle simple case where list is not nested
                simple = True
                for i in range(len(val)):
                    if not (type(val[i]) in [types.BooleanType, types.FloatType, 
                                         types.IntType,  types.StringType,
                                         types.UnicodeType, types.NoneType,
                                         types.LongType]):
                        simple = False
                        break

                if simple: 
                    self.msg(fns.columnize_array(val, self.width))
                    return False
                
            self.msg(pprint.pformat(val))
        except:
            pass

    def do_pwd(self, arg):
        "Print working directory."
        self.msg('Working directory ' + os.getcwd() + '.')

    def do_pydoc(self, arg):
        """pydoc <name> ...

Show pydoc documentation on something. <name> may be the name of a
Python keyword, topic, function, module, or package, or a dotted
reference to a class or function within a module or module in a
package.  If <name> contains a '/', it is used as the path to a Python
source file to document. If name is 'keywords', 'topics', or
'modules', a listing of these things is displayed.
"""
        sys_path_save = list(sys.path)
        sys_argv_save = list(sys.argv)
        sys.argv      = ['pydoc'] + shlex.split(arg)
        pydoc.cli()
        sys.argv      = sys_argv_save
        sys.path      = sys_path_save
        return False

    def do_python(self, arg_str):
        """python 

Run python as a command subshell.
"""

        # See if python's code module is around
        try:
            from code import interact
        except ImportError:
            self.msg("python code doesn't seem to be importable.")
            return False

        # Python does it's own history thing.
        # Make sure it doesn't damage ours.
        if hasattr(self, 'readline') and self.readline:
            try:
                self.write_history_file()
            except IOError:
                pass

        local = None
        if self.curframe:
            if self.curframe.f_locals:
                local = dict(self.curframe.f_locals)
                local.update(self.curframe.f_globals)
            else:
                local = self.curframe.f_globals
            pass

        if local:
            interact(banner='Pydb python shell', local=local)
        else:
            interact(banner='Pydb python shell')

        # Restore our history if we can do so.
        if hasattr(self, 'readline') and self.readline and self.histfile is not None:
            try:
                self.readline.read_history_file(self.histfile)
            except IOError:
                pass
            return False
        return False

    def do_quit(self, arg):
        """q(uit) or exit - Quit the debugger.  The program being
        executed is aborted."""
        if self.target != 'local':
            self._rebind_output(self.orig_stdout)
            self._rebind_input(self.orig_stdin)
            self._disconnect()
            self.target = 'local'

        sys.settrace(None)
        self._user_requested_quit = True
        self.running              = False
        self.set_quit()

        # Tell cmdloop to break out of its loop.
        return True

    do_q = do_quit

    def do_restart(self, arg):
        """restart - Restart debugger and program via an exec
        call. All state is lost, and new copy of the debugger is used."""

        # We don't proceed with the restart until the action has been
        # ACK'd by any connected clients
        if self.connection != None:
            self.msg('restarting (connection)')
            line = ""
            while not 'ACK:restart_now' in line:
                line = self.connection.readline()
            self.do_rquit(None)
        else:
            if self._sys_argv[0]:
                self.msg("Re exec'ing:\n\t%s" % self._sys_argv)
                os.execvp(self._sys_argv[0], self._sys_argv)
            else:
                self.msg("No exectuable file specified.")
        return False
        

    def do_return(self, arg):
        """Make selected stack frame return to its caller. Control
        remains in the debugger, but when you continue execution will
        resume at the return statement found inside the subroutine or
        method.  At present we are only able to perform this if we are
        in a subroutine that has a 'return' statement in it."""
        if not self.is_running(): return
        frame = self.curframe

        if '?' == frame.f_code.co_name and not '__args__' in frame.f_locals:
            self.errmsg("I don't see that we are in a subroutine.")
            return

        while True and not self.noninteractive:
            try:
                # reply = raw_input('Make %s return now? (y or n) ')
                reply = raw_input('Return now? (y or n) ').strip()
            except EOFError:
                reply = 'no'
                reply = reply.strip().lower()
            if reply in ('y', 'yes'):
                break
            elif reply in ('n', 'no'):
                return
            else:
                self.msg("Please answer y or n.")

        co = frame.f_code
        code = co.co_code
        labels = dis.findlabels(code)
        linestarts = dict(dis.findlinestarts(co))

        i=frame.f_lasti
        last_line = inspect.getlineno(frame)
        # last_stmt = i
        # print "++i: %d, len(code): %d" % (i, len(code))
        while i < len(code):
            i += 1
            if i in labels:
                # print "++last_stmt %d" % i
                # last_stmt = i
                last_line = None
            if i in linestarts and i > 0:
                # print "++last_line %d" % linestarts[i]
                last_line = linestarts[i]
            if 'RETURN_VALUE' == op_at_frame(frame, i):
                break

        if i == len(self.stack) or last_line is None:
            self.msg("Sorry; a return statement was not found.")
            return

        # print "++i: %d, last_stmt %d, line: %d " % (i, last_stmt, last_line)
        self.do_jump(last_line, "Return")
        return False

    def do_run(self, arg_str):
        """run [args...]

        Run or "soft" restart the debugged Python program. If a string
is supplied, it is splitted with "shlex" but preserving embedded quotes.
The result is used as the new sys.argv.  History, breakpoints, actions
and debugger options are preserved. R is a alias for 'run'.

See also 'restart' for an exec-like restart."""
        if not self._program_sys_argv:
            self.errmsg("No Python program registered.")
            self.errmsg("Perhaps you want to use the 'file' command?")
            return
        if arg_str:
            argv_start = self._program_sys_argv[0:1]
            self._program_sys_argv = arg_split(arg_str)
            self._program_sys_argv[:0] = argv_start

        raise Restart

    do_R = do_run

    def do_save(self, arg):
        """save [all|break|settings] [filename]
        Save specified settings to a file as a script
Use the 'source' command in another debug session to restore them."""
        args = arg.split()
        actions = ['all', 'break', 'settings']
        filename = os.path.expanduser("~/pydb-restart.txt")
        if 0 == len(args):
            what = 'all'
        elif 1 == len(args):
            if args[0] in actions:
                what = args[0]
            else:
                filename = os.path.expanduser(args[0])
                what = 'all'
        elif 2 == len(args):
            what = args[0]
            if args[0] not in actions:
                self.errmsg("Action has to be 'all', 'break' or 'settings; " 
                            "got '%s'." % args[0])
                return False
            filename = os.path.expanduser(args[1])
        else: 
            # len(args) > 2:
            self.errmsg("Expecting 0-2 arguments, got %d." % len(args))
            return False
        restart_file = open(filename, 'w')
        what_str = ''
        if what in ('all', 'break'):
            lines = self.output_break_commands()
            restart_file.write("\n".join(lines) + "\n")
            what_str = 'Breakpoints'
        if what in ('all', 'settings'):
            if '' == what_str:
                what_str = 'Settings'
            else:
                what_str = 'Settings and breakpoints'
            for subcommand in self.setcmds.list():
                if subcommand in ['args', 'debug-pydb', 'history', 'logging', 
                                  'prompt', 'trace-commands', 'warnoptions']: 
                                  continue
                # commands that have lots of output we can't handle right now.
                if not self.showcmds.subcmds[subcommand]['in_list']:
                    continue
                val = eval('self.get_%s()' % subcommand)
                restart_file.write('set %s %s\n' % (subcommand, val))
        if what_str != '':
            restart_file.close()
            self.msg('%s saved to file %s' % (what_str, restart_file.name))
            return False
        return False

    def do_set(self, arg):
        """See help_set"""
        args = arg.split()
        if len(args) == 1 and 'warnoptions'.startswith(args[0]):
            self.setcmds.do(self, args[0], args)
            return
        if len(args) < 2:
            self.errmsg("Expecting at least 2 arguments, got %d." % len(args))
            return False
        self.setcmds.do(self, args[0], args)
        return False

    def do_shell(self, arg):
        """Execute the rest of the line as a shell command."""
        os.system(arg)
        return False

    def do_show(self, arg):

        """Generic command for showing things about the debugger.  You
        can give unique prefix of the name of a subcommand to get info
        about just that subcommand."""

        if not arg:
            for subcommand in self.showcmds.list():
                # Some commands have lots of output.
                # they are excluded here because 'in_list' is false.
                if self.showcmds.subcmds[subcommand]['in_list']:
                    self.msg_nocr("%s: " % subcommand)
                    self.do_show(subcommand)
            return False

        if self._re_linetrace_delay.match(arg):
            self.msg("line trace delay is %s. (In seconds)"
                     % self.linetrace_delay)
        else:
            args = arg.split()
            self.showcmds.do(self, args[0], args)

        return False
            
    def do_signal(self, arg):
        """signal [signum|signame]

Send a signal to the debugged process.
"""
        if arg =='':
            signum = 0
        else:
            try: 
                signum = int(eval(arg))
                if sighandler.lookup_signame(signum) == None:
                    self.msg("Signal number %d not a known signal number."
                             % signum)
                    return
            except ValueError:
                signum = sighandler.lookup_signum(arg)
                if signum == None:
                    self.msg("Signal name %s not a known signal name."
                             % arg)
                    return
        os.kill(os.getpid(), signum)
        return False
        
    def do_skip(self, arg):
        """skip [count]

        Set the next line that will be executed. The line must be within
        the stopped or bottom-most execution frame frame."""

        if not self.is_running(): return None

        if self.curindex + 1 != len(self.stack):
            self.errmsg("You can only skip within the bottom frame.")
            return None

        if self.curframe.f_trace is None:
            self.errmsg("Sigh - operation can't be done here.")
            return None
        
        try:
            count = self.get_pos_int(arg, default=1, cmdname='skip')
        except ValueError:
            return None
        co = self.curframe.f_code
        offset = self.curframe.f_lasti
        if count is None: return False
        lineno = bytecode.next_linestart(co, offset, count)

        if lineno < 0:
            self.errmsg('No next line found')
            return False

        try:
            # Set to change position, update our copy of the stack,
            # and display the new position
            self.curframe.f_lineno = lineno
            self.stack[self.curindex] = self.stack[self.curindex][0], lineno
            self.print_location()
        except ValueError, e:
            self.errmsg('skip failed: %s' % e)
        return None

    def do_source(self, arg):
        """source [-v] FILE
        Read debugger commands from a file named FILE.
        Optional -v switch (before the filename) causes each command in
        FILE to be echoed as it is executed.
        Note that the file '.pydbrc' is read automatically
        in this way when pydb is started.

        An error in any command terminates execution of the command
        file and control is returned to the console."""
        args = arg.split()
        verbose=False
        if len(args) == 2 and args[0] == '-v': 
            arg=args[1]
            verbose=True
        self.setup_source(os.path.expanduser(arg), True);
        rc = self.execRcLines(verbose)
        if rc == 1:  return True
        return False

    def do_step(self, arg):
        """s(tep) [count]
Execute the current line, stop at the first possible occasion
(either in a function that is called or in the current function).

With an integer argument, step that many times."""
        if not self.is_running(): return None
        try:
            # 0 means stop now or step 1, so we subtract 1.
            self.step_ignore = self.get_pos_int(arg, default=1,
                                                cmdname='step') - 1
        except ValueError:
            return

        self.stepping = True  # Used in thread debugging
        self.set_step()
        # Tell cmdloop to break out of its loop.
        return True

    do_s = do_step

    def do_tbreak(self, arg, thread_name=None):
        """tbreak  [ ([filename:]lineno | function) [, condition] ]
        Set a temporary breakpoint. Arguments are like the "break" command.
        Like "break" except the breakoint is only temporary,
        so it will be deleted when hit."""
        self.do_break(arg, 1, thread_name)

    def do_unalias(self, arg):
        """unalias name
Deletes the specified alias."""
        args = arg.split()
        if len(args) == 0: return
        if args[0] in self.aliases:
            del self.aliases[args[0]]
        return False

    # Print a traceback starting at the top stack frame.
    # The most recently entered frame is printed last;
    # this is different from dbx and gdb, but consistent with
    # the Python interpreter's stack trace.
    # It is also consistent with the up/down commands (which are
    # compatible with dbx and gdb: up moves towards 'main()'
    # and down moves towards the most recent stack frame).

    def do_undisplay(self, arg):
        """Cancel some expressions to be displayed when program stops.
        Arguments are the code numbers of the expressions to stop displaying.
        No argument means cancel all automatic-display expressions.
        "delete display" has the same effect as this command.
        Do "info display" to see current list of code numbers."""

        if arg:
            args = arg.split()
            if len(args) == 1:
                self.display.clear()
                return
            for i in args:
                i = self.get_an_int(i, 'index %r is not a number' % i)
                if i is not None:
                    if not self.display.delete_index(i):
                        self.errmsg("No display number %d." % i)
                        return
                    pass
                pass
        return False

    def do_up(self, arg):
        """up [count]
        Move the current frame one level up in the stack trace
        (to an older frame).

        If using gdb dialect up matches the gdb: 0 is the most recent
        frame.  Otherwise we match Python's stack: 0 is the oldest
        frame.  """

        try:
            count = self.get_int(arg, cmdname="up")
        except ValueError:
            return
        if self.gdb_dialect:
            count = -count
        self.__adjust_frame(pos=count, absolute_pos=False)
        return False

    def do_whatis(self, arg):
        """whatis arg
Prints the type of the argument which can be a Python expression."""
        try:
            if not self.curframe:
                # ?? Should we have set up a dummy globals
                # to have persistence?
                value = eval(arg, None, None)
            else:
                value = eval(arg, self.curframe.f_globals,
                             self.curframe.f_locals)
        except:
            t, v = sys.exc_info()[:2]
            if type(t) == types.StringType:
                exc_type_name = t
            else: exc_type_name = t.__name__
            if exc_type_name == 'NameError':
                self.errmsg("Name Error: %s" % arg)
            else:
                self.errmsg("%s: %s" % (exc_type_name, self._saferepr(v)))
            return False
        if inspect.ismethod(value):
            self.msg('method %s%s' %
                     (value.func_code.co_name,
                       inspect.formatargspec(inspect.getargspec(value))))
            if inspect.getdoc(value):
                self.msg('%s:\n%s' %
                         (value, inspect.getdoc(value)))
            return False
        elif inspect.isfunction(value):
            self.msg('function %s%s' %
                     (value.func_code.co_name,
                       inspect.formatargspec(inspect.getargspec(value))))
            if inspect.getdoc(value):
                self.msg('%s:\n%s' %
                         (value, inspect.getdoc(value)))
            return False
        # None of the above...
        self.msg(type(value))
        return False

    def do_where(self, arg):
        """where [count]

        Print a stack trace, with the most recent frame at the top.
        With a positive number, print at most many entries.
        An arrow indicates the 'current frame', which determines the
        context of most commands.  'bt' and 'T' are short command
        names for this."""

        try:
            count = self.get_pos_int(arg, default=None, cmdname="where")
        except ValueError:
            return False

        if not self.curframe:
            self.msg("No stack.")
            return False
        print_stack_trace(self, count)
        return False

    do_T = do_bt = do_where

    def do_EOF(self, arg):
        """EOF
Handles the receipt of EOF as a command."""
        self.msg("")
        self._user_requested_quit = True
        self.set_quit()

        # Tell cmdloop to break out of its loop.
        return True

    #########################################################
    # Help methods (derived from pydb.doc or vice versa)
    #########################################################

    for fn in ('EOF',     'alias',     'break',
               'cd',      'clear',     'condition',   'continue',
               'debug',   'disable',   'delete'   ,   'disassemble',
               'display', 'down',      'enable',      'examine',
               'finish',  'frame',     'help',
               'ignore',  'info',      'jump',        'list',
               'next',    'p',         'pp',          'pwd',    'quit',
               'restart', 'retval',    'run',
               'set',     'show',      'shell',       'source', 'step',
               'tbreak',  'unalias',   'undisplay',   'up',
               'whatis',  'where'):
        exec 'def help_%s(self, *arg): self.msg(self.do_%s.__doc__)' \
             % (fn, fn)

    # Is this the right way to do this?
    ## Remove duplicate short names
    ## help_h = help_help
    ## help_R = help_run
    ## help_bt = help_T = help_where

    def help_commands(self, *arg):
        print """commands [bpnumber]
>...
>end
(Pydb)

Set commands to be executed when a breakpoint is hit.
Give breakpoint number as the argument after "commands".
With no bpnumber argument, commands refers to the last one set.
The commands themselves follow starting on the next line.
Type a line containing "end" to terminate the commands.

To remove all commands from a breakpoint, type commands and
follow it immediately with end; that is, give no commands.

You can use breakpoint commands to start your program up
again. Simply use the continue command, or step, or any other
command that resumes execution.

Specifying any command resuming execution (currently continue, step,
next, return, jump, and quit) terminates the command list as if that
command was immediately followed by 'end'.  This is because any time
you resume execution (even with a simple next or step), you may
encounter another breakpoint--which could have its own command list,
leading to ambiguities about which list to execute.

If you use the 'silent' command in the command list, the
usual message about stopping at a breakpoint is not printed.
This may be desirable for breakpoints that are to print a
specific message and then continue.  If none of the other
commands print anything, you see no sign that the breakpoint
was reached.
"""

    def help_exec(self, *arg):
        self.msg("""(!) statement
        Execute the (one-line) statement in the context of
        the current stack frame.
        The exclamation point can be omitted unless the first word
        of the statement resembles a debugger command.
        To assign to a global variable you must always prefix the
        command with a 'global' command, e.g.:
        %sglobal list_options; list_options = ['-l']
        %s""" % (self.prompt, self.prompt))
        return

    # Note: format of help is compatible with ddd.
    def help_info(self, args):
        """Generic command for showing things about the program being debugged."""
        if len(args) == 0:
            self.infocmds.help(self, '')
        else:
            self.infocmds.help(self, args[0])
            return
        return

    # Note: format of help is compatible with ddd.
    def help_set(self, args):
        """This command modifies parts of the debugger environment.
You can see these environment settings with the 'show' command."""
        if len(args) == 0:
            self.setcmds.help(self, '')
        else:
            self.setcmds.help(self, args[0])
            return
        return

    # Note: format of help is compatible with ddd.
    def help_show(self, args):
        """Generic command for showing things about the debugger."""
        if len(args) == 0:
            self.showcmds.help(self, '')
        else:
            self.showcmds.help(self, args[0])
            return
        return

    def help_unalias(self):
        print """unalias name
Deletes the specified alias."""
        return

    ####### End of help section ########
#
# Local variables:
#  mode: Python
# End: