This file is indexed.

/usr/lib/python2.7/dist-packages/plasTeX/Context.py is in python-plastex 0.9.2-1.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
import new, os, ConfigParser, re, time, codecs
import plasTeX
from plasTeX import ismacro, macroName
from plasTeX.DOM import Node
from plasTeX.Logging import getLogger
from Tokenizer import Tokenizer, Token, DEFAULT_CATEGORIES, VERBATIM_CATEGORIES

# Only export the Context singleton
__all__ = ['Context']

# Set up loggers
log = getLogger()
status = getLogger('status')
stacklog = getLogger('context.stack')
macrolog = getLogger('context.macros')


class ContextItem(dict):
    """ 
    Localized macro/category code stack element

    """

    def __init__(self, data={}):
        dict.__init__(self, data)
        self.categories = None
        self.obj = None
        self.parent = None
        self.owner = None

    @property
    def name(self):
        if self.obj is not None:
            return self.obj.nodeName
        return '{}'

    def __getitem__(self, key):
        try: 
            return dict.__getitem__(self, key)
        except KeyError:
            if self.parent is not None:
                return self.parent[key]
            raise

    def get(self, key, default=None):
        try: return self[key]
        except KeyError: return default

    def has_key(self, key):
        if dict.has_key(self, key):
            return True
        if self.parent is not None:
            return self.parent.has_key(key)

    __contains__ = has_key

    def keys(self):
        keys = {}
        for key in dict.keys(self):
            keys[key] = 0
        if self.parent is not None:
            for key in self.parent.keys():
                keys[key] = 0
        return keys.keys()

    def __str__(self):
        if self.parent is not None:
             return '%s -> %s' % (self.parent, self.name)
        return self.name


class Counters(dict):
    def __getitem__(self, name):
        try: 
            c = dict.__getitem__(self, name)
        except KeyError:
#           log.warning('No counter "%s" exists.  Creating one.' % name)
            c = self[name] = plasTeX.Counter(self.context, name)
        return c


class LanguageParser(object):
    """ Parser for language commands """

    def __init__(self, output={}):
        self.data = output
        self.language = None
        self.term = None

    def parse(self, files, encoding='utf8'):
        from xml.parsers import expat
        if isinstance(files, basestring):
            files = [files]
        for file in files:
            if not os.path.isfile(file):
                continue
            self.parser = expat.ParserCreate()
            self.parser.StartElementHandler = self.startElement
            self.parser.EndElementHandler = self.endElement
            self.parser.CharacterDataHandler = self.charData
            self.parser.Parse(codecs.open(file, 'r', encoding).read())
        self.mergeLanguages()
        return self.data

    def mergeLanguages(self):
        # Merge language keys from the major language section, into
        # the minor language section
        for key, value in self.data.items():
            if '-' in key:
                major, minor = key.split('-',1)
                if major in self.data:
                    majordict = self.data[major]
                    for mkey, mvalue in majordict.items():
                        if mkey not in value:
                            value[mkey] = mvalue

    def startElement(self, name, attrs):
        if name == 'terms':
            self.term = None
            if self.data.get(attrs['lang']):
                self.language = self.data[attrs['lang']] 
            else:
                self.language = self.data[attrs['lang']] = {}
            if 'babel' in attrs:
                self.data[attrs['babel']] = self.language
        elif name == 'term':
            self.term = attrs['name']
            self.language[self.term] = u''
            
    def endElement(self, name):
        if name == 'term':
            self.term = None
            
    def charData(self, data):
        if self.term:
            self.language[self.term] += data


class Context(object):
    """
    Object to handle macro contexts within a TeX document

    This class keeps track of macros (both global and local), labels,
    context groupings, category codes, etc.  The TeX parser uses this
    class to hold any and all information about the document currently
    being processed.  This class also contains methods to generate 
    new counters, ifs, dimensions, and other commands and macros.

    """

    def globals(self):
        return self.contexts[0]

    def __init__(self, load=False):
        # Stack of ContextItems
        self.contexts = []

        # Object that the current label points to
        self.currentlabel = None

        # Labeled objects
        self.labels = {}
        self.persistentLabels = {}

        # Unresolved refs
        self.refs = {}

        # LaTeX counters
        self.counters = Counters()
        self.counters.context = self

        # Tokens aliased by \let
        self.lets = {}

        # Imported packages and their options
        self.packages = {}

        # Output files
        self.writes = {}

        # Depth of the context stack
        self.depth = 0

        # Holds the current environment name stack
        self._currenvir = []

        # Holds the terms for various languages
        self.languages = {}
        self.terms = {}
        self.currentLanguage = ''

        # Create a global namespace
        self.push()

        self.warnOnUnrecognized = True

        if load:
            self.loadBaseMacros()

    def currenvir():
        def fget(self):
            if self._currenvir:
                return self._currenvir[-1]
            return
        def fset(self, value):
            if value is None:
                self._currenvir.pop()
            else:
                self._currenvir.append(value)
        def fdel(self):
            self._currenvir.pop()
        return locals()
    currenvir = property(**currenvir())

    def persist(self, filename, rtype='none'):
        """
        Persist cross-document information for labeled nodes

        Required Arguments:
        filename -- the name of the file with the shelved data
 
        Keyword Arguments:
        rtype -- the key in the shelved data to look under.  This is generally
            the name of the renderer used since the information for each
            renderer may be different.

        """
        import pickle
        if os.path.exists(filename):
            try:
                d = pickle.load(open(filename,'rb'))
                if rtype not in d:
                    d[rtype] = {}
            except:
                os.remove(filename)
                d = {rtype:{}}
        else:
            d = {rtype:{}}
        data = d[rtype]
        for key, value in self.persistentLabels.items():
            data[key] = value.persist()
        try:
            pickle.dump(d, open(filename,'wb'))
        except Exception, msg:
            log.warning('Could not save auxiliary information. (%s)' % msg)

    def restore(self, filename, rtype='none'):
        """
        Restore cross-document information for labeled nodes

        Required Arguments:
        filename -- the name of the file with the shelved data
 
        Keyword Arguments:
        rtype -- the key in the shelved data to look under.  This is generally
            the name of the renderer used since the information for each
            renderer may be different.

        """
        import pickle
        if not os.path.exists(filename):
            return
        try:
            d = pickle.load(open(filename,'rb'))
            try: data = d[rtype]
            except KeyError: return
            wou = self.warnOnUnrecognized
            self.warnOnUnrecognized = False
            for key, value in data.items():
                n = self[value.get('macroName','Macro')]()
                n.restore(value)
                self.labels[key] = n
            self.warnOnUnrecognized = wou
        except Exception, msg:
            log.warning('Could not load auxiliary information. (%s)' % msg)

    @property
    def isMathMode(self):
        """ Are we in math mode or not? """
        for i in range(len(self.contexts)-1, -1, -1):
            obj = self.contexts[i].obj
            if obj is not None and obj.mathMode is not None:
                return obj.mathMode
        return False

    def loadBaseMacros(self):
        """ Import all builtin macros """
        from plasTeX import Base
        self.importMacros(vars(Base))

    def loadLanguage(self, lang, document):
        """
        Load a localized version of macros for a particular language

        Required Arguments:
        lang -- the name of the language file to load

        """
        if not self.languages:
            files = document.config['document']['lang-terms'].split(os.pathsep)
            files.append(os.path.join(os.path.dirname(__file__), 'i18n.xml'))
            LanguageParser(self.languages).parse(reversed(files))

        if lang in self.languages:
            self.currentLanguage = lang
            self.newcommand('languagename', definition=lang)
            self.terms = self.languages[lang]
            for key, value in self.languages[lang].items():
                if key == 'today':
                    self.newcommand(key, definition=self._strftime(value))                
                else:
                    self.newcommand('%sname' % key, definition=value)
        else:
            log.warning('Could not load language "%s", american will be used instead' % lang)

    def _strftime(self, fmt):
        if '%f' not in fmt:
            return time.strftime(fmt)
            
        day = time.strftime('%e')
        suffix = 'th'
        if day.endswith('1'):
            suffix = 'st'
        elif day.endswith('2'):
            suffix = 'nd'
        elif day.endswith('3'):
            suffix = 'rd'
        return time.strftime(fmt.replace('%f', '%e'+suffix))

    def loadINIPackage(self, inifile):
        """ 
        Load INI file containing macro definitions

        Arguments:
        inifile -- filename of INI formatted file

        """
        ini = ConfigParser.RawConfigParser()
        if not isinstance(inifile, (list,tuple)):
            inifile = [inifile]
        for f in inifile:
            ini.read(f)
            macros = {}
            for section in ini.sections():
                try: baseclass = self[section]
                except KeyError:
                    log.warning('Could not find macro %s' % section)
                    continue
                for name in ini.options(section):
                    value = ini.get(section,name)
                    m = re.match(r'^unicode\(\s*(?:(\'|\")(?P<string>.+)(?:\1)|(?P<number>\d+))\s*\)$',value)
                    if m:
                        data = m.groupdict()
                        if data['number'] is not None:
                            value = unichr(int(data['number']))
                        else:
                            value = unicode(data['string'])
                        macros[name] = new.classobj(name, (baseclass,), 
                                                    {'unicode': value})
                        continue 
                    macros[name] = new.classobj(name, (baseclass,), 
                                                {'args': value})
            self.importMacros(macros)

    def loadPackage(self, tex, file, options={}):
        """
        Load a Python or LaTeX package

        A Python version of the package is searched for first,
        if one cannot be found then a LaTeX version of the package
        is searched for.

        Required Arguments:
        tex -- the instance of the TeX engine to use for parsing
            the LaTeX file, if needed.
        file -- the name of the file to load

        Keyword Arguments:
        options -- the options given on the macro to pass to the package

        Returns:
        boolean indicating whether or not the package loaded successfully

        """
        module = os.path.splitext(file)[0]

        # See if it has already been loaded
        if self.packages.has_key(module):
            return True

        packagesini = os.path.join(os.path.dirname(plasTeX.Packages.__file__), 
                                   os.path.basename(module)+'.ini')

        try: 
            # Try to import a Python package by that name
            m = __import__(module, globals(), locals())
            status.info(' ( %s ' % m.__file__)
            if hasattr(m, 'ProcessOptions'):
                m.ProcessOptions(options or {}, tex.ownerDocument)
            self.importMacros(vars(m))
            moduleini = os.path.splitext(m.__file__)[0]+'.ini'
            self.loadINIPackage([packagesini, moduleini])
            self.packages[module] = options
            status.info(' ) ')
            return True

        except ImportError, msg:
            # No Python module
            if 'No module' in str(msg):
                pass
                # Failed to load Python package
#               log.warning('No Python version of %s was found' % file)
            # Error while importing
            else:
                raise

        result = tex.loadPackage(file, options)
        try:
            moduleini = os.path.join(os.path.dirname(tex.kpsewhich(file)),
                                     os.path.basename(module)+'.ini')
            self.loadINIPackage([packagesini, moduleini])
        except OSError: pass
        return result
   

    def label(self, label, node=None):
        """ 
        Set a label to the current labelable object

        Required Arguments:
        label -- string that contains the label

        Keyword Arguments:
        node -- a node to apply the label to rather than the currently
            labelable object

        See Also:
        self.ref()

        """
        label = label.strip()
        if not label:
            return

        if node is None:
            node = self.currentlabel

        if node is not None:
            self.persistentLabels[label] = self.labels[label] = node
            node.id = label

        #print label, ''.join(self.currentlabel.ref[:])

        # Resolve any outstanding references to this object
        if self.refs.has_key(label) and self.labels.has_key(label):
            for obj in self.refs[label]:
                for key, value in obj.idref.items():
                    if value.id != label:
                        continue
                    obj.idref[key] = self.labels[label]
            del self.refs[label]

    def ref(self, obj, name, label):
        """
        Set up a ref for resolution

        Required Arguments:
        obj -- object to put the referenced object onto
        name -- name of key in idref dictionary where object is stored
        label -- label to resolve

        See Also:
        self.label()

        """
        label = label.strip()
        if not label:
            return

        # Resolve ref if label already exists
        if self.labels.has_key(label):
            obj.idref[name] = self.labels[label]
            return 

        # If the label doesn't exist, store away the object for later
        if not self.refs.has_key(label):
            self.refs[label] = []
        self.refs[label].append(obj)

        # Make a fake node with the ID on it for now
        node = self['Macro']()
        node.id = label
        obj.idref[name] = node

    def __getitem__(self, key):
        """ 
        Look through the stack of macros and return the requested one 

        Required Arguments:
        key -- name of macro

        Returns: instance of requested macro

        """
        try: return self.top[key]
        except KeyError: pass

        # Didn't find it, so generate a new class
        if self.warnOnUnrecognized and not self.isMathMode:
            log.warning('unrecognized command/environment: %s', key)
        self[key] = newclass = new.classobj(str(key), (plasTeX.UnrecognizedMacro,), {})
        return newclass

    def push(self, context=None):
        """ 
        Add a new context to the stack 

        This adds a new context grouping to the stack.  A context
        grouping includes both a set of localized macros and localized
        category codes.

        Keyword Arguments:
        context -- macro instance to use as the basis for a context
            grouping.  The local macros and category codes of this
            instance are used.  If this argument isn't supplied,
            an empty context is created.

        """
        if not self.contexts:
            context = ContextItem()
            context.categories = DEFAULT_CATEGORIES[:]
            self.contexts.append(context)

        else:
            name = '{}'
            if context is not None:
                name = context.nodeName 
                # If we hit a document element, make sure that we start
                # at the global context.
                if context.level == context.DOCUMENT_LEVEL:
                    while len(self.contexts) > 1:
                        self.contexts.pop()
            stacklog.debug('pushing %s onto %s', name, self.top)
            self.contexts.append(self.createContext(context))

        self.mapMethods()

    append = push

    def mapMethods(self):
        # Getter methods use the most local context
        self.top = top = self.contexts[-1]
        self.__getitem__ = top.__getitem__
        self.__contains__ = top.__contains__
        self.get = top.get
        self.keys = top.keys
        self.has_key = top.has_key
        self.categories = top.categories

        # Setter methods always use the global namespace
        self.update = top.update
        self.__setitem__ = self.contexts[0].__setitem__

        # Set up inheritance attributes
        self.top.owner = self
        if len(self.contexts) > 1:
            self.top.parent = self.contexts[-2]

        self.depth = len(self.contexts)

    def createContext(self, obj=None):
        """
        Create the pieces of a new context (i.e. macros and category codes)

        Keyword Arguments:
        obj -- macro instance to use as the basis for a context
            grouping.  The local macros and category codes of this
            instance are used.  If this argument isn't supplied,
            an empty context is created.

        Returns: ContextItem instance 

        """
        newcontext = ContextItem()
        newcontext.categories = self.categories
        newcontext.obj = obj

        if obj is not None:

            # Get the local category codes and macros
#           if obj.categories is not None:
#               newcontext.categories = obj.categories

            newcontext.update(obj.locals())

        return newcontext

    def importMacros(self, context):
        """ 
        Import macros from given context into the global namespace

        Required Arguments:
        context -- dictionary of macros to import

        """
        for value in context.values():
            if ismacro(value):
                self[macroName(value)] = value
#           elif isinstance(value, Context):
#               self.importMacros(value)

    def pop(self, obj=None):
        """ 
        Remove a context from the stack 

        Keyword Arguments:
        index -- index of context item to remove

        Returns: ContextItem instance removed from stack

        """
#       print 'POP', type(obj).__name__, self.contexts[-1]
        if obj is None:
            # Pop until we hit a None in the context
            while len(self.contexts) > 1:
                if self.contexts[-1].obj is None:
                    self.contexts.pop()
                    break
                self.contexts.pop()
        else:
            while len(self.contexts) > 1:
                o = self.contexts[-1].obj
                # If None, keep going
                if o is None:
                    pass
                # Found context pushed by ourself
                elif o is obj:
                    self.contexts.pop()
                    break
                # Don't pop parent node
                elif o is obj.parentNode:
                    break
                # Found the \begin to our \end
                elif type(obj) == type(o) and obj.macroMode == obj.MODE_END:
                    self.contexts.pop()
                    break
                # Found the \foo to our \endfoo
                elif obj.nodeName == ('end%s' % o.nodeName):
                    self.contexts.pop()
                    break
                self.contexts.pop()

        self.mapMethods()

    def addGlobal(self, key, value):
        """ 
        Add a macro to the global context 

        Required Arguments:
        key -- name of macro to add
        value -- item to add to the global namespace.  If the item
            is a macro instance, it is simply added to the namespace.
            If it is a string, it is converted into a string Command
            instance before being added.

        """
        if isinstance(value, basestring):
            newvalue = plasTeX.Command()
            newvalue.unicode = value
            value = newvalue

        elif not ismacro(value):
            raise ValueError, \
                  '"%s" does not implement the macro interface' % key

        self.contexts[0][macroName(value)] = value

    __setitem__ = addGlobal

    def addLocal(self, key, value):
        """ 
        Add a macro to the local context 

        Required Arguments:
        key -- name of macro to add
        value -- item to add to the global namespace.  If the item
            is a macro instance, it is simply added to the namespace.
            If it is a string, it is converted into a string Command
            instance before being added.

        """
        if isinstance(value, basestring):
            newvalue = plasTeX.Command()
            newvalue.unicode = value
            value = newvalue

        elif not ismacro(value):
            raise ValueError, \
                  '"%s" does not implement the macro interface' % key

        self.contexts[-1][macroName(value)] = value

    def whichCode(self, char):
        """ 
        Return the character code that `char` belongs to 

        Required Arguments:
        char -- character to determine the code of

        Returns: integer category code of the given character

        """
        c = self.categories
        if char in c[Token.CC_LETTER]:
            return Token.CC_LETTER
        if char in c[Token.CC_SPACE]:
            return Token.CC_SPACE
        if char in c[Token.CC_EOL]:
            return Token.CC_EOL
        if char in c[Token.CC_BGROUP]:
            return Token.CC_BGROUP
        if char in c[Token.CC_EGROUP]:
            return Token.CC_EGROUP 
        if char in c[Token.CC_ESCAPE]:
            return Token.CC_ESCAPE 
        if char in c[Token.CC_SUPER]:
            return Token.CC_SUPER
        if char in c[Token.CC_SUB]:
            return Token.CC_SUB 
        if char in c[Token.CC_MATHSHIFT]:
            return Token.CC_MATHSHIFT
        if char in c[Token.CC_ALIGNMENT]:
            return Token.CC_ALIGNMENT 
        if char in c[Token.CC_COMMENT]:
            return Token.CC_COMMENT
        if char in c[Token.CC_ACTIVE]:
            return Token.CC_ACTIVE
        if char in c[Token.CC_PARAMETER]:
            return Token.CC_PARAMETER
        if char in c[Token.CC_IGNORED]:
            return Token.CC_IGNORED 
        if char in c[Token.CC_INVALID]:
            return Token.CC_INVALID
        return Token.CC_OTHER

    def catcode(self, char, code):
        """
        Set the category code for a particular character
 
        Required arguments:
        char -- the character to set the code of
        code -- the category code number to set `char` to

        """
        c = self.contexts[-1].categories = self.categories = self.categories[:]
        for i in range(0,16):
            c[i] = c[i].replace(char, '')
        # Don't insert if it's code 12.
        if code != 12:
            c[code] += char

    def setVerbatimCatcodes(self):
        """
        Set the category codes up for parsing verbatims

        This method turns the category codes for all characters to CC_OTHER

        """
        self.contexts[-1].categories = self.categories = VERBATIM_CATEGORIES[:]

    def newcounter(self, name, resetby=None, initial=0, format=None):
        """ 
        Create a new counter 

        This method corresponds to LaTeX's \\newcounter command

        Required Arguments:
        name -- name of the counter.  The generate counter class will
            use this name.  Also, a new macro called 'the<name>' will
            also be generated for the counter format.

        Keyword Arguments:
        resetby -- the name of the counter that this counter is reset by
        initial -- initial value for the counter

        """
        name = str(name)
        # Counter already exists
        if self.counters.has_key(name):
            macrolog.debug('counter %s already defined', name)
            return
        self.counters[name] = plasTeX.Counter(self, name, resetby, initial)

        if format is None:
            format = '${%s}' % name
        newclass = new.classobj('the'+name, (plasTeX.TheCounter,), 
                               {'format': format})
        self.addGlobal('the'+name, newclass)

    def newwrite(self, name, file):
        """
        Create a new output file

        Required Arguments:
        name -- the key name for the file
        file -- the file name to open

        """
        self.writes[name] = open(file, 'w')

    def newcount(self, name, initial=0):
        """ 
        Create a new count (like \\newcount)

        Required Arguments:
        name -- name of count to create
      
        Keyword Arguments:
        initial -- value to initialize to

        """
        name = str(name)
        # Generate a new count class
        macrolog.debug('creating count %s', name)
        newclass = new.classobj(name, (plasTeX.CountCommand,), 
                               {'value': plasTeX.count(initial)})
        self.addGlobal(name, newclass)

    def newdimen(self, name, initial=0):
        """ 
        Create a new dimen (like \\newdimen)

        Required Arguments:
        name -- name of dimen to create
      
        Keyword Arguments:
        initial -- value to initialize to

        """
        name = str(name)
        # Generate a new dimen class
        macrolog.debug('creating dimen %s', name)
        newclass = new.classobj(name, (plasTeX.DimenCommand,), 
                                {'value': plasTeX.dimen(initial)})
        self.addGlobal(name, newclass)

    def newskip(self, name, initial=0):
        """ 
        Create a new glue (like \\newskip)

        Required Arguments:
        name -- name of glue to create
      
        Keyword Arguments:
        initial -- value to initialize to

        """
        name = str(name)
        # Generate a new glue class
        macrolog.debug('creating dimen %s', name)
        newclass = new.classobj(name, (plasTeX.GlueCommand,), 
                                {'value': plasTeX.glue(initial)})
        self.addGlobal(name, newclass)

    def newmuskip(self, name, initial=0):
        """ 
        Create a new muglue (like \\newmuskip)

        Required Arguments:
        name -- name of muglue to create
      
        Keyword Arguments:
        initial -- value to initialize to

        """
        name = str(name)
        # Generate a new muglue class
        macrolog.debug('creating muskip %s', name)
        newclass = new.classobj(name, (plasTeX.MuGlueCommand,), 
                                {'value': plasTeX.muglue(initial)})
        self.addGlobal(name, newclass)

    def newif(self, name, initial=False):
        """ 
        Create a new \\if (and accompanying) commands 

        This method corresponds to TeX's \\newif command.

        Required Arguments:
        name -- name of the 'if' command.  This name should always
            start with the letters 'if'.

        Keyword Arguments:
        initial -- initial value of the 'if' command

        """        
        name = str(name)
        # \if already exists
        if self.has_key(name):
            macrolog.debug('if %s already defined', name)
            return

        # Generate new 'if' class
        macrolog.debug('creating if %s', name)
        ifclass = new.classobj(name, (plasTeX.NewIf,), {'state':initial})
        self.addGlobal(name, ifclass)

        # Create \iftrue macro
        truename = name[2:]+'true'
        newclass = new.classobj(truename, (plasTeX.IfTrue,), {'ifclass':ifclass})
        self.addGlobal(truename, newclass)

        # Create \iffalse macro
        falsename = name[2:]+'false'
        newclass = new.classobj(falsename, (plasTeX.IfFalse,), {'ifclass':ifclass})
        self.addGlobal(falsename, newclass)

    def newcommand(self, name, nargs=0, definition=None, opt=None):
        """ 
        Create a \\newcommand 

        Required Arguments:
        name -- name of the macro to create
        nargs -- integer number of arguments that the macro has
        definition -- string containing the LaTeX definition
        opt -- string containing the LaTeX code to use in the 
            optional argument

        Examples::
            c.newcommand('bold', 1, r'\\textbf{#1}')
            c.newcommand('foo', 2, r'{\\bf #1#2}', opt='myprefix')

        """
        name = str(name)
        # Macro already exists
        if self.has_key(name):
            if not issubclass(self[name], (plasTeX.NewCommand, 
                                           plasTeX.Definition)):
                if not issubclass(self[name], plasTeX.TheCounter):
                    return
            macrolog.debug('redefining command "%s"', name)

        if nargs is None:
            nargs = 0
        assert isinstance(nargs, int), 'nargs must be an integer'
        
        if isinstance(definition, basestring):
            definition = [x for x in Tokenizer(definition, self)]
        
        if isinstance(opt, basestring):
            opt = [x for x in Tokenizer(opt, self)]

        macrolog.debug('creating newcommand %s', name)
        newclass = new.classobj(name, (plasTeX.NewCommand,),
                       {'nargs':nargs,'opt':opt,'definition':definition})

        self.addGlobal(name, newclass)

    def newenvironment(self, name, nargs=0, definition=None, opt=None):
        """ 
        Create a \\newenvironment 

        Required Arguments:
        name -- name of the macro to create
        nargs -- integer number of arguments that the macro has
        definition -- two-element tuple containing the LaTeX definition.
            Each element should be a string.  The first element 
            corresponds to the beginning of the environment, and the
            second element is the end of the environment.
        opt -- string containing the LaTeX code to use in the 
            optional argument

        Examples::
            c.newenvironment('mylist', 0, (r'\\begin{itemize}', r'\\end{itemize}'))

        """
        name = str(name)
        # Macro already exists
        if self.has_key(name):
            if not issubclass(self[name], (plasTeX.NewCommand, 
                                           plasTeX.Definition)):
                return
            macrolog.debug('redefining environment "%s"', name)

        if nargs is None:
            nargs = 0
        assert isinstance(nargs, int), 'nargs must be an integer'

        if definition is not None:
            assert isinstance(definition, (tuple,list)), \
                'definition must be a list or tuple'
            assert len(definition) == 2, 'definition must have 2 elements'

            if isinstance(definition[0], basestring):
                definition[0] = [x for x in Tokenizer(definition[0], self)]
            if isinstance(definition[1], basestring):
                definition[1] = [x for x in Tokenizer(definition[1], self)]

        if isinstance(opt, basestring):
            opt = [x for x in Tokenizer(opt, self)]

        macrolog.debug('creating newenvironment %s', name)

        # Begin portion
        newclass = new.classobj(name, (plasTeX.NewCommand,),
                       {'nargs':nargs,'opt':opt,'definition':definition[0]})
        self.addGlobal(name, newclass)

        # End portion
        newclass = new.classobj('end'+name, (plasTeX.NewCommand,),
                       {'nargs':0,'opt':None,'definition':definition[1]})
        self.addGlobal('end' + name, newclass)

    def newdef(self, name, args=None, definition=None, local=True):
        """ 
        Create a \def 

        Required Arguments:
        name -- name of the macro to create
        args -- string containing the TeX argument profile
        definition -- string containing the LaTeX definition
      
        Keyword Arguments:
        local -- indicates whether this macro is local or global

        Examples::
            c.newdef('bold', '#1', '{\\bf #1}')
            c.newdef('put', '(#1,#2)#3', '\\dostuff{#1}{#2}{#3}')

        """
        name = str(name)
        # Macro already exists
#       if self.has_key(name):
#           if not issubclass(self[name], (plasTeX.NewCommand, 
#                                          plasTeX.Definition)):
#               return
#           macrolog.debug('redefining definition "%s"', name)

        if isinstance(definition, basestring):
            definition = [x for x in Tokenizer(definition, self)]

        macrolog.debug('creating def %s', name)
        newclass = new.classobj(name, (plasTeX.Definition,),
                       {'args':args,'definition':definition})

        if local:
            self.addLocal(name, newclass)
        else:
            self.addGlobal(name, newclass)

    def let(self, dest, source):
        """
        Create a \let

        Required Arguments:
        dest -- the command sequence to create
        source -- the token to set the command sequence equivalent to

        Examples::
            c.let('bgroup', BeginGroup('{'))

        """
        self.lets[dest] = source

    def chardef(self, name, num):
        """ 
        Create a \\chardef

        Required Arguments:
        name -- name of command to create
        num -- character number to use
      
        """
        name = str(name)
        # Generate a new chardef class
        macrolog.debug('creating chardef %s', name)
        newclass = new.classobj(name, (plasTeX.Command,), 
                                {'unicode':chr(num)})
        self.addGlobal(name, newclass)