bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def get(self, section, option, raw=0): """Get an option value for a given section.
def get(self, section, option, raw=0): """Get an option value for a given section.
7,400
def visitImport(self, node): self.set_lineno(node) for name, alias in node.names: if VERSION > 1: self.emit('LOAD_CONST', None) self.emit('IMPORT_NAME', name) mod = name.split(".")[0] self.storeName(alias or mod)
def visitImport(self, node): self.set_lineno(node) for name, alias in node.names: if VERSION > 1: self.emit('LOAD_CONST', None) self.emit('IMPORT_NAME', name) mod = name.split(".")[0] self.storeName(alias or mod)
7,401
def get_content_type(self): """Returns the message's content type.
def get_content_type(self): """Returns the message's content type.
7,402
def get_content_maintype(self): """Returns the message's main content type.
def get_content_maintype(self): """Returns the message's main content type.
7,403
def get_content_subtype(self): """Returns the message's sub content type.
def get_content_subtype(self): """Returns the message's sub content type.
7,404
def open_debugger(self): import Debugger self.interp.setdebugger(Debugger.Debugger(self)) sys.ps1 = "[DEBUG ON]>>> " self.showprompt() self.top.tkraise() self.text.focus_set()
def open_debugger(self): import Debugger self.interp.setdebugger(Debugger.Debugger(self)) sys.ps1 = "[DEBUG ON]\n>>> " self.showprompt() self.top.tkraise() self.text.focus_set()
7,405
def open_debugger(self): import Debugger self.interp.setdebugger(Debugger.Debugger(self)) sys.ps1 = "[DEBUG ON]>>> " self.showprompt() self.top.tkraise() self.text.focus_set()
def open_debugger(self): import Debugger self.interp.setdebugger(Debugger.Debugger(self)) sys.ps1 = "[DEBUG ON]>>> " self.showprompt() self.top.tkraise() self.text.focus_set()
7,406
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) except (TypeError, IOError): raise IOError, 'could not get source code' lines = file.readlines() file.close() if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 pat = re.compile(r'^\s*def\s') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError, 'could not find code object'
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" file = getsourcefile(object) or getfile(object) lines = linecache.getlines(file) if not lines: raise IOError, 'could not get source code' lines = file.readlines() file.close() if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 pat = re.compile(r'^\s*def\s') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError, 'could not find code object'
7,407
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) except (TypeError, IOError): raise IOError, 'could not get source code' lines = file.readlines() file.close() if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 pat = re.compile(r'^\s*def\s') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError, 'could not find code object'
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) except (TypeError, IOError): raise IOError, 'could not get source code' if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 pat = re.compile(r'^\s*def\s') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError, 'could not find code object'
7,408
def getframeinfo(frame, context=1): """Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line.""" if istraceback(frame): frame = frame.tb_frame if not isframe(frame): raise TypeError, 'arg is not a frame or traceback object' filename = getsourcefile(frame) lineno = getlineno(frame) if context > 0: start = lineno - 1 - context//2 try: lines, lnum = findsource(frame) except IOError: lines = index = None else: start = max(start, 1) start = min(start, len(lines) - context) lines = lines[start:start+context] index = lineno - 1 - start else: lines = index = None return (filename, lineno, frame.f_code.co_name, lines, index)
def getframeinfo(frame, context=1): """Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line.""" if istraceback(frame): frame = frame.tb_frame if not isframe(frame): raise TypeError, 'arg is not a frame or traceback object' filename = getsourcefile(frame) or getfile(frame) lineno = getlineno(frame) if context > 0: start = lineno - 1 - context//2 try: lines, lnum = findsource(frame) except IOError: lines = index = None else: start = max(start, 1) start = min(start, len(lines) - context) lines = lines[start:start+context] index = lineno - 1 - start else: lines = index = None return (filename, lineno, frame.f_code.co_name, lines, index)
7,409
def readline(self): import EasyDialogs # A trick to make the input dialog box a bit more palatable if hasattr(sys.stdout, '_buf'): prompt = sys.stdout._buf else: prompt = "" if not prompt: prompt = "Stdin input:" sys.stdout.flush() rv = EasyDialogs.AskString(prompt) if rv is None: return "" return rv + '\n'
def readline(self): import EasyDialogs # A trick to make the input dialog box a bit more palatable if hasattr(sys.stdout, '_buf'): prompt = sys.stdout._buf else: prompt = "" if not prompt: prompt = "Stdin input:" sys.stdout.flush() rv = EasyDialogs.AskString(prompt) if rv is None: return "" return rv + '\n'
7,410
def _docdescriptor(self, name, value, mod): results = [] push = results.append
def _docdescriptor(self, name, value, mod): results = [] push = results.append
7,411
def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: if callable(value) or inspect.isdatadescriptor(value): doc = getattr(value, "__doc__", None) else: doc = None push(self.docother(getattr(object, name), name, mod, 70, doc) + '\n') return attrs
def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: if callable(value) or inspect.isdatadescriptor(value): doc = getdoc(value) else: doc = None push(self.docother(getattr(object, name), name, mod, 70, doc) + '\n') return attrs
7,412
def __str__(self): return self.x
def __str__(self): return self.x
7,413
def __str__(self): return self.x
def __str__(self): return self.x
7,414
def test_SEH(self): # Call functions with invalid arguments, and make sure that access violations # are trapped and raise an exception. # # Normally, in a debug build of the _ctypes extension # module, exceptions are not trapped, so we can only run # this test in a release build. import sys if not hasattr(sys, "getobjects"): self.assertRaises(WindowsError, windll.kernel32.GetModuleHandleA, 32)
def test_SEH(self): # Call functions with invalid arguments, and make sure that access violations # are trapped and raise an exception. # # Normally, in a debug build of the _ctypes extension # module, exceptions are not trapped, so we can only run # this test in a release build. import sys if not hasattr(sys, "getobjects"): self.assertRaises(WindowsError, windll.kernel32.GetModuleHandleA, 32)
7,415
def connect_ftp(self, user, passwd, host, port, dirs): key = user, passwd, host, port if key in self.cache: self.timeout[key] = time.time() + self.delay else: self.cache[key] = ftpwrapper(user, passwd, host, port, dirs) self.timeout[key] = time.time() + self.delay self.check_cache() return self.cache[key]
def connect_ftp(self, user, passwd, host, port, dirs): key = user, host, port, '/'.join(dirs) if key in self.cache: self.timeout[key] = time.time() + self.delay else: self.cache[key] = ftpwrapper(user, passwd, host, port, dirs) self.timeout[key] = time.time() + self.delay self.check_cache() return self.cache[key]
7,416
def __format(self, object, stream, indent, allowance, context, level):
def __format(self, object, stream, indent, allowance, context, level):
7,417
def __format(self, object, stream, indent, allowance, context, level):
def __format(self, object, stream, indent, allowance, context, level):
7,418
def _getDefaults(cls): defaults = {} for name, value in cls.__dict__.items(): if name[0] != "_" and not isinstance(value, (function, classmethod)): defaults[name] = deepcopy(value) for base in cls.__bases__: if hasattr(base, "_getDefaults"): defaults.update(base._getDefaults()) return defaults
def _getDefaults(cls): defaults = {} for name, value in cls.__dict__.items(): if name[0] != "_" and not isinstance(value, (function, classmethod)): defaults[name] = deepcopy(value) return defaults
7,419
def _parse(source, state, flags=0): # parse regular expression pattern into an operator list. subpattern = SubPattern(state) while 1: if source.next in ("|", ")"): break # end of subpattern this = source.get() if this is None: break # end of pattern if state.flags & SRE_FLAG_VERBOSE: # skip whitespace and comments if this in WHITESPACE: continue if this == "#": while 1: this = source.get() if this in (None, "\n"): break continue if this and this[0] not in SPECIAL_CHARS: subpattern.append((LITERAL, this)) elif this == "[": # character set set = []
def_parse(source,state,flags=0):#parseregularexpressionpatternintoanoperatorlist.subpattern=SubPattern(state)while1:ifsource.nextin("|",")"):break#endofsubpatternthis=source.get()ifthisisNone:break#endofpatternifstate.flags&SRE_FLAG_VERBOSE:#skipwhitespaceandcommentsifthisinWHITESPACE:continueifthis=="#":while1:this=source.get()ifthisin(None,"\n"):breakcontinueifthisandthis[0]notinSPECIAL_CHARS:subpattern.append((LITERAL,this))elifthis=="[":#charactersetset=[]
7,420
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated index" if char == ">": break # FIXME: check for valid character name = name + char if not name: raise error, "bad index" try: index = int(name) except ValueError: try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown index" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: while s.next in DIGITS: this = this + s.get() a((MARK, int(this[1:]))) else: try: a(ESCAPES[this]) except KeyError: for char in this: a((LITERAL, char)) else: a((LITERAL, this)) return p
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated group name" if char == ">": break # FIXME: check for valid character name = name + char if not name: raise error, "bad index" try: index = int(name) except ValueError: try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown index" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: while s.next in DIGITS: this = this + s.get() a((MARK, int(this[1:]))) else: try: a(ESCAPES[this]) except KeyError: for char in this: a((LITERAL, char)) else: a((LITERAL, this)) return p
7,421
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated index" if char == ">": break # FIXME: check for valid character name = name + char if not name: raise error, "bad index" try: index = int(name) except ValueError: try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown index" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: while s.next in DIGITS: this = this + s.get() a((MARK, int(this[1:]))) else: try: a(ESCAPES[this]) except KeyError: for char in this: a((LITERAL, char)) else: a((LITERAL, this)) return p
defparse_template(source,pattern):#parse're'replacementstringintolistofliteralsand#groupreferencess=Tokenizer(source)p=[]a=p.appendwhile1:this=s.get()ifthisisNone:break#endofreplacementstringifthisandthis[0]=="\\":ifthis=="\\g":name=""ifs.match("<"):while1:char=s.get()ifcharisNone:raiseerror,"unterminatedindex"ifchar==">":break#FIXME:checkforvalidcharactername=name+charifnotname:raiseerror,"badindex"try:index=int(name)exceptValueError:try:index=pattern.groupindex[name]exceptKeyError:raiseIndexError,"unknownindex"a((MARK,index))eliflen(this)>1andthis[1]inDIGITS:whiles.nextinDIGITS:this=this+s.get()a((MARK,int(this[1:])))else:try:a(ESCAPES[this])exceptKeyError:forcharinthis:a((LITERAL,char))else:a((LITERAL,this))returnp
7,422
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated index" if char == ">": break # FIXME: check for valid character name = name + char if not name: raise error, "bad index" try: index = int(name) except ValueError: try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown index" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: while s.next in DIGITS: this = this + s.get() a((MARK, int(this[1:]))) else: try: a(ESCAPES[this]) except KeyError: for char in this: a((LITERAL, char)) else: a((LITERAL, this)) return p
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated index" if char == ">": break # FIXME: check for valid character name = name + char if not name: raise error, "bad group name" try: index = int(name) except ValueError: try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown index" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: while s.next in DIGITS: this = this + s.get() a((MARK, int(this[1:]))) else: try: a(ESCAPES[this]) except KeyError: for char in this: a((LITERAL, char)) else: a((LITERAL, this)) return p
7,423
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated index" if char == ">": break # FIXME: check for valid character name = name + char if not name: raise error, "bad index" try: index = int(name) except ValueError: try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown index" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: while s.next in DIGITS: this = this + s.get() a((MARK, int(this[1:]))) else: try: a(ESCAPES[this]) except KeyError: for char in this: a((LITERAL, char)) else: a((LITERAL, this)) return p
def parse_template(source, pattern): # parse 're' replacement string into list of literals and # group references s = Tokenizer(source) p = [] a = p.append while 1: this = s.get() if this is None: break # end of replacement string if this and this[0] == "\\": if this == "\\g": name = "" if s.match("<"): while 1: char = s.get() if char is None: raise error, "unterminated index" if char == ">": break # FIXME: check for valid character name = name + char if not name: raise error, "bad index" try: index = int(name) except ValueError: try: index = pattern.groupindex[name] except KeyError: raise IndexError, "unknown group name" a((MARK, index)) elif len(this) > 1 and this[1] in DIGITS: while s.next in DIGITS: this = this + s.get() a((MARK, int(this[1:]))) else: try: a(ESCAPES[this]) except KeyError: for char in this: a((LITERAL, char)) else: a((LITERAL, this)) return p
7,424
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
7,425
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
7,426
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
7,427
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
def any_err(func, *args): try: apply(func, args) except (struct.error, OverflowError, TypeError): pass else: raise TestFailed, "%s%s did not raise error" % ( func.__name__, args)
7,428
def test_native_qQ(): bytes = struct.calcsize('q') # The expected values here are in big-endian format, primarily because # I'm on a little-endian machine and so this is the clearest way (for # me) to force the code to get exercised. for format, input, expected in ( ('q', -1, '\xff' * bytes), ('q', 0, '\x00' * bytes), ('Q', 0, '\x00' * bytes), ('q', 1L, '\x00' * (bytes-1) + '\x01'), ('Q', (1L << (8*bytes))-1, '\xff' * bytes), ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))): got = struct.pack(format, input) native_expected = bigendian_to_native(expected) verify(got == native_expected, "%r-pack of %r gave %r, not %r" % (format, input, got, native_expected)) retrieved = struct.unpack(format, got)[0] verify(retrieved == input, "%r-unpack of %r gave %r, not %r" % (format, got, retrieved, input))
def test_native_qQ(): bytes = struct.calcsize('q') # The expected values here are in big-endian format, primarily because # I'm on a little-endian machine and so this is the clearest way (for # me) to force the code to get exercised. for format, input, expected in ( ('q', -1, '\xff' * bytes), ('q', 0, '\x00' * bytes), ('Q', 0, '\x00' * bytes), ('q', 1L, '\x00' * (bytes-1) + '\x01'), ('Q', (1L << (8*bytes))-1, '\xff' * bytes), ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))): got = struct.pack(format, input) native_expected = bigendian_to_native(expected) verify(got == native_expected, "%r-pack of %r gave %r, not %r" % (format, input, got, native_expected)) retrieved = struct.unpack(format, got)[0] verify(retrieved == input, "%r-unpack of %r gave %r, not %r" % (format, got, retrieved, input))
7,429
def test_one_qQ(x, pack=struct.pack, unpack=struct.unpack, unhexlify=binascii.unhexlify): if verbose: print "trying std q/Q on", x, "==", hex(x) # Try 'q'. if MIN_q <= x <= MAX_q: # Try '>q'. expected = long(x) if x < 0: expected += 1L << 64 assert expected > 0 expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (8 - len(expected)) + expected # >q pack work? got = pack(">q", x) verify(got == expected, "'>q'-pack of %r gave %r, not %r" % (x, got, expected)) # >q unpack work? retrieved = unpack(">q", got)[0] verify(x == retrieved, "'>q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, ">q", '\x01' + got) # Try '<q'. expected = string_reverse(expected) # <q pack work? got = pack("<q", x) verify(got == expected, "'<q'-pack of %r gave %r, not %r" % (x, got, expected)) # <q unpack work? retrieved = unpack("<q", got)[0] verify(x == retrieved, "'<q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, "<q", '\x01' + got) else: # x is out of q's range -- verify pack realizes that. any_err(pack, '>q', x) any_err(pack, '<q', x) # Much the same for 'Q'. if MIN_Q <= x <= MAX_Q: # Try '>Q'. expected = long(x) expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (8 - len(expected)) + expected # >Q pack work? got = pack(">Q", x) verify(got == expected, "'>Q'-pack of %r gave %r, not %r" % (x, got, expected)) # >Q unpack work? retrieved = unpack(">Q", got)[0] verify(x == retrieved, "'>Q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, ">Q", '\x01' + got) # Try '<Q'. expected = string_reverse(expected) # <Q pack work? got = pack("<Q", x) verify(got == expected, "'<Q'-pack of %r gave %r, not %r" % (x, got, expected)) # <Q unpack work? retrieved = unpack("<Q", got)[0] verify(x == retrieved, "'<Q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, "<Q", '\x01' + got) else: # x is out of Q's range -- verify pack realizes that. any_err(pack, '>Q', x) any_err(pack, '<Q', x)
def test_one_qQ(x, pack=struct.pack, unpack=struct.unpack, unhexlify=binascii.unhexlify): if verbose: print "trying std q/Q on", x, "==", hex(x) # Try 'q'. if MIN_q <= x <= MAX_q: # Try '>q'. expected = long(x) if x < 0: expected += 1L << 64 assert expected > 0 expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (8 - len(expected)) + expected # >q pack work? got = pack(">q", x) verify(got == expected, "'>q'-pack of %r gave %r, not %r" % (x, got, expected)) # >q unpack work? retrieved = unpack(">q", got)[0] verify(x == retrieved, "'>q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, ">q", '\x01' + got) # Try '<q'. expected = string_reverse(expected) # <q pack work? got = pack("<q", x) verify(got == expected, "'<q'-pack of %r gave %r, not %r" % (x, got, expected)) # <q unpack work? retrieved = unpack("<q", got)[0] verify(x == retrieved, "'<q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, "<q", '\x01' + got) else: # x is out of q's range -- verify pack realizes that. any_err(pack, '>q', x) any_err(pack, '<q', x) # Much the same for 'Q'. if MIN_Q <= x <= MAX_Q: # Try '>Q'. expected = long(x) expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (8 - len(expected)) + expected # >Q pack work? got = pack(">Q", x) verify(got == expected, "'>Q'-pack of %r gave %r, not %r" % (x, got, expected)) # >Q unpack work? retrieved = unpack(">Q", got)[0] verify(x == retrieved, "'>Q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, ">Q", '\x01' + got) # Try '<Q'. expected = string_reverse(expected) # <Q pack work? got = pack("<Q", x) verify(got == expected, "'<Q'-pack of %r gave %r, not %r" % (x, got, expected)) # <Q unpack work? retrieved = unpack("<Q", got)[0] verify(x == retrieved, "'<Q'-unpack of %r gave %r, not %r" % (got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, "<Q", '\x01' + got) else: # x is out of Q's range -- verify pack realizes that. any_err(pack, '>Q', x) any_err(pack, '<Q', x)
7,430
def visitModule(self, node): stmt = node.node found_docstring = False for s in stmt.nodes: # Skip over docstrings if not found_docstring and isinstance(s, ast.Discard) \ and isinstance(s.expr, ast.Const) \ and isinstance(s.expr.value, str): found_docstring = True continue if not self.check_stmt(s): break
def visitModule(self, node): stmt = node.node for s in stmt.nodes: # Skip over docstrings if not found_docstring and isinstance(s, ast.Discard) \ and isinstance(s.expr, ast.Const) \ and isinstance(s.expr.value, str): found_docstring = True continue if not self.check_stmt(s): break
7,431
def visitModule(self, node): stmt = node.node found_docstring = False for s in stmt.nodes: # Skip over docstrings if not found_docstring and isinstance(s, ast.Discard) \ and isinstance(s.expr, ast.Const) \ and isinstance(s.expr.value, str): found_docstring = True continue if not self.check_stmt(s): break
def visitModule(self, node): stmt = node.node found_docstring = False for s in stmt.nodes: # Skip over docstringsif not self.check_stmt(s): break
7,432
def _formatparam(param, value=None, quote=1): """Convenience function to format and return a key=value pair. Will quote the value if needed or if quote is true. """ if value is not None and len(value) > 0: # BAW: Please check this. I think that if quote is set it should # force quoting even if not necessary. if quote or tspecials.search(value): return '%s="%s"' % (param, Utils.quote(value)) else: return '%s=%s' % (param, value) else: return param
def _formatparam(param, value=None, quote=1): """Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. """ if value is not None and len(value) > 0: # BAW: Please check this. I think that if quote is set it should # force quoting even if not necessary. if quote or tspecials.search(value): return '%s="%s"' % (param, Utils.quote(value)) else: return '%s=%s' % (param, value) else: return param
7,433
def get_params(self, failobj=None, header='content-type', unquote=1): """Return the message's Content-Type: parameters, as a list.
def get_params(self, failobj=None, header='content-type', unquote=1): """Return the message's Content-Type: parameters, as a list.
7,434
def get_param(self, param, failobj=None, header='content-type', unquote=1): """Return the parameter value if found in the Content-Type: header.
def get_param(self, param, failobj=None, header='content-type', unquote=1): """Return the parameter value if found in the Content-Type: header.
7,435
def get_filename(self, failobj=None): """Return the filename associated with the payload if present.
def get_filename(self, failobj=None): """Return the filename associated with the payload if present.
7,436
def get_boundary(self, failobj=None): """Return the boundary associated with the payload if present.
def get_boundary(self, failobj=None): """Return the boundary associated with the payload if present.
7,437
def initialize_options (self):
def initialize_options (self):
7,438
def nextfile(self): savestdout = self._savestdout self._savestdout = 0 if savestdout: sys.stdout = savestdout
def nextfile(self): savestdout = self._savestdout self._savestdout = 0 if savestdout: sys.stdout = savestdout
7,439
def readline(self): try: line = self._buffer[self._bufindex] except IndexError: pass else: self._bufindex += 1 self._lineno += 1 self._filelineno += 1 return line if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = False self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = True else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or os.extsep+"bak")) try: os.unlink(self._backupfilename) except os.error: pass # The next few lines may raise IOError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, "r") try: perm = os.fstat(self._file.fileno()).st_mode except: self._output = open(self._filename, "w") else: fd = os.open(self._filename, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, perm) self._output = os.fdopen(fd, "w") try: os.chmod(self._filename, perm) except: pass self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise IOError self._file = open(self._filename, "r") self._buffer = self._file.readlines(self._bufsize) self._bufindex = 0 if not self._buffer: self.nextfile() # Recursive call return self.readline()
def readline(self): try: line = self._buffer[self._bufindex] except IndexError: pass else: self._bufindex += 1 self._lineno += 1 self._filelineno += 1 return line if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = False self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = True else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or os.extsep+"bak")) try: os.unlink(self._backupfilename) except os.error: pass # The next few lines may raise IOError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, "r") try: perm = os.fstat(self._file.fileno()).st_mode except OSError: self._output = open(self._filename, "w") else: fd = os.open(self._filename, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, perm) self._output = os.fdopen(fd, "w") try: os.chmod(self._filename, perm) except OSError: pass self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise IOError self._file = open(self._filename, "r") self._buffer = self._file.readlines(self._bufsize) self._bufindex = 0 if not self._buffer: self.nextfile() # Recursive call return self.readline()
7,440
def readline(self): try: line = self._buffer[self._bufindex] except IndexError: pass else: self._bufindex += 1 self._lineno += 1 self._filelineno += 1 return line if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = False self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = True else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or os.extsep+"bak")) try: os.unlink(self._backupfilename) except os.error: pass # The next few lines may raise IOError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, "r") try: perm = os.fstat(self._file.fileno()).st_mode except: self._output = open(self._filename, "w") else: fd = os.open(self._filename, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, perm) self._output = os.fdopen(fd, "w") try: os.chmod(self._filename, perm) except: pass self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise IOError self._file = open(self._filename, "r") self._buffer = self._file.readlines(self._bufsize) self._bufindex = 0 if not self._buffer: self.nextfile() # Recursive call return self.readline()
def readline(self): try: line = self._buffer[self._bufindex] except IndexError: pass else: self._bufindex += 1 self._lineno += 1 self._filelineno += 1 return line if not self._file: if not self._files: return "" self._filename = self._files[0] self._files = self._files[1:] self._filelineno = 0 self._file = None self._isstdin = False self._backupfilename = 0 if self._filename == '-': self._filename = '<stdin>' self._file = sys.stdin self._isstdin = True else: if self._inplace: self._backupfilename = ( self._filename + (self._backup or os.extsep+"bak")) try: os.unlink(self._backupfilename) except os.error: pass # The next few lines may raise IOError os.rename(self._filename, self._backupfilename) self._file = open(self._backupfilename, "r") try: perm = os.fstat(self._file.fileno()).st_mode except OSError: self._output = open(self._filename, "w") else: fd = os.open(self._filename, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, perm) self._output = os.fdopen(fd, "w") try: os.chmod(self._filename, perm) except OSError: pass self._savestdout = sys.stdout sys.stdout = self._output else: # This may raise IOError self._file = open(self._filename, "r") self._buffer = self._file.readlines(self._bufsize) self._bufindex = 0 if not self._buffer: self.nextfile() # Recursive call return self.readline()
7,441
def pushing(name, point, depth): dbgmsg("%s<%s> at %s" % (" "*depth, name, point))
def pushing(name, point, depth): dbgmsg("pushing <%s> at %s" % (name, point))
7,442
def popping(name, point, depth): dbgmsg("%s</%s> at %s" % (" "*depth, name, point))
def popping(name, point, depth): dbgmsg("%s</%s> at %s" % (" "*depth, name, point))
7,443
def __init__(self, ifp, ofp, table=None, discards=(), autoclosing=()): self.ofp_stack = [ofp] self.pop_output() self.table = table self.discards = discards self.autoclosing = autoclosing self.line = string.join(map(string.rstrip, ifp.readlines()), "\n") self.err_write = sys.stderr.write self.preamble = 1
def __init__(self, ifp, ofp, table=None, discards=(), autoclosing=()): self.ofp_stack = [ofp] self.pop_output() self.table = table self.discards = discards self.autoclosing = autoclosing self.line = string.join(map(string.rstrip, ifp.readlines()), "\n") self.preamble = 1
7,444
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
def subconvert(self, endchar=None, depth=0): stack = self.stack line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = self.stack self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
7,445
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
7,446
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
7,447
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
def subconvert(self, endchar=None, depth=0):line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code:self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
7,448
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: raise LaTeXStackError(envname, stack) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
7,449
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
7,450
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
7,451
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
7,452
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: if DEBUG: self.err_write("subconvert() --> %s\n" % `line[1:21]`) self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
def subconvert(self, endchar=None, depth=0): stack = [] line = self.line if DEBUG and endchar: self.err_write( "subconvert(%s)\n line = %s\n" % (`endchar`, `line[:20]`)) while line: if line[0] == endchar and not stack: self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: # re-write to use the macro handler line = r"\%s %s" % (m.group(1), line[m.end():]) continue m = _end_env_rx.match(line) if m: # end of environment envname = m.group(1) if envname == "document": # special magic for n in stack[1:]: if n not in self.autoclosing: raise LaTeXFormatError( "open element on stack: " + `n`) # should be more careful, but this is easier to code: stack = [] self.write(")document\n") elif stack and envname == stack[-1]: self.write(")%s\n" % envname) del stack[-1] popping(envname, "a", len(stack) + depth) else: self.err_write("stack: %s\n" % `stack`) raise LaTeXFormatError( "environment close for %s doesn't match" % envname) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: # start of macro macroname = m.group(1) if macroname == "verbatim": # really magic case! pos = string.find(line, "\\end{verbatim}") text = line[m.end(1):pos] self.write("(verbatim\n") self.write("-%s\n" % encode(text)) self.write(")verbatim\n") line = line[pos + len("\\end{verbatim}"):] continue numbered = 1 opened = 0 if macroname[-1] == "*": macroname = macroname[:-1] numbered = 0 if macroname in self.autoclosing and macroname in stack: while stack[-1] != macroname: top = stack.pop() if top and top not in self.discards: self.write(")%s\n-\\n\n" % top) popping(top, "b", len(stack) + depth) if macroname not in self.discards: self.write("-\\n\n)%s\n-\\n\n" % macroname) popping(macroname, "c", len(stack) + depth - 1) del stack[-1] # if macroname in self.discards: self.push_output(StringIO.StringIO()) else: self.push_output(self.ofp) # params, optional, empty, environ = self.start_macro(macroname) if not numbered: self.write("Anumbered TOKEN no\n") # rip off the macroname if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] # # Very ugly special case to deal with \item[]. The catch # is that this needs to occur outside the for loop that # handles attribute parsing so we can 'continue' the outer # loop. # if optional and type(params[0]) is TupleType: # the attribute name isn't used in this special case pushing(macroname, "a", depth + len(stack)) stack.append(macroname) self.write("(%s\n" % macroname) m = _start_optional_rx.match(line) if m: self.line = line[m.end():] line = self.subconvert("]", depth + len(stack)) line = "}" + line continue # handle attribute mappings here: for attrname in params: if optional: optional = 0 if type(attrname) is StringType: m = _optional_rx.match(line) if m: line = line[m.end():] self.write("A%s TOKEN %s\n" % (attrname, encode(m.group(1)))) elif type(attrname) is TupleType: # This is a sub-element; but place the and attribute # we found on the stack (\section-like); the # content of the macro will become the content # of the attribute element, and the macro will # have to be closed some other way (such as # auto-closing). pushing(macroname, "b", len(stack) + depth) stack.append(macroname) self.write("(%s\n" % macroname) macroname = attrname[0] m = _start_group_rx.match(line) if m: line = line[m.end():] elif type(attrname) is ListType: # A normal subelement: <macroname><attrname>...</>... attrname = attrname[0] if not opened: opened = 1 self.write("(%s\n" % macroname) pushing(macroname, "c", len(stack) + depth) self.write("(%s\n" % attrname) pushing(attrname, "sub-elem", len(stack) + depth + 1) self.line = skip_white(line)[1:] line = self.subconvert("}", len(stack) + depth + 1)[1:] popping(attrname, "sub-elem", len(stack) + depth + 1) self.write(")%s\n" % attrname) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (attrname, macroname, `line[:100]`)) value = m.group(1) if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (attrname, dtype, encode(value))) line = line[m.end():] if params and type(params[-1]) is StringType \ and (not empty) and not environ: # attempt to strip off next '{' m = _start_group_rx.match(line) if not m: raise LaTeXFormatError( "non-empty element '%s' has no content: %s" % (macroname, line[:12])) line = line[m.end():] if not opened: self.write("(%s\n" % macroname) pushing(macroname, "d", len(stack) + depth) if empty: line = "}" + line stack.append(macroname) self.pop_output() continue if line[0] == endchar and not stack: self.line = line[1:] return self.line if line[0] == "}": # end of macro or group macroname = stack[-1] conversion = self.table.get(macroname) if macroname \ and macroname not in self.discards \ and type(conversion) is not StringType: # otherwise, it was just a bare group self.write(")%s\n" % stack[-1]) popping(macroname, "d", len(stack) + depth - 1) del stack[-1] line = line[1:] continue if line[0] == "{": pushing("", "e", len(stack) + depth) stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue # special case because of \item[] if line[0] == "]": self.write("-]\n") line = line[1:] continue # avoid infinite loops extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack and stack[-1] in self.autoclosing: self.write("-\\n\n") self.write(")%s\n" % stack[-1]) popping(stack.pop(), "e", len(stack) + depth - 1) if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) # otherwise we just ran out of input here...
7,453
def convert(self): self.subconvert()
def convert(self): self.subconvert()
7,454
def convert(ifp, ofp, table={}, discards=(), autoclosing=()): c = Conversion(ifp, ofp, table, discards, autoclosing) try: c.convert() except IOError, (err, msg): if err != errno.EPIPE: raise
class NewConversion(BaseConversion): def __init__(self, ifp, ofp, table={}): BaseConversion.__init__(self, ifp, ofp, table) self.discards = [] def subconvert(self, endchar=None, depth=0): stack = new_stack() line = self.line while line: if line[0] == endchar and not stack: self.line = line return line m = _comment_rx.match(line) if m: text = m.group(1) if text: self.write("(COMMENT\n- %s \n)COMMENT\n-\\n\n" % encode(text)) line = line[m.end():] continue m = _begin_env_rx.match(line) if m: name = m.group(1) entry = self.get_env_entry(name) line = r"\%s %s" % (name, line[m.end():]) continue m = _end_env_rx.match(line) if m: envname = m.group(1) entry = self.get_entry(envname) while stack and envname != stack[-1] \ and stack[-1] in entry.endcloses: self.write(")%s\n" % stack.pop()) if stack and envname == stack[-1]: self.write(")%s\n" % entry.outputname) del stack[-1] else: raise LaTeXStackError(envname, stack) line = line[m.end():] continue m = _begin_macro_rx.match(line) if m: macroname = m.group(1) entry = self.get_entry(macroname) if entry.verbatim: pos = string.find(line, "\\end{%s}" % macroname) text = line[m.end(1):pos] stack.append(entry.name) self.write("(%s\n" % entry.outputname) self.write("-%s\n" % encode(text)) self.write(")%s\n" % entry.outputname) stack.pop() line = line[pos + len("\\end{%s}" % macroname):] continue while stack and stack[-1] in entry.closes: top = stack.pop() topentry = self.get_entry(top) if topentry.outputname: self.write(")%s\n-\\n\n" % topentry.outputname) if entry.outputname: if entry.empty: self.write("e\n") self.push_output(self.ofp) else: self.push_output(StringIO.StringIO()) params, optional, empty, environ = self.start_macro(macroname) if params: line = line[m.end(1):] elif empty: line = line[m.end(1):] else: line = line[m.end():] opened = 0 implied_content = 0 for pentry in params: if pentry.type == "attribute": if pentry.optional: m = _optional_rx.match(line) if m: line = line[m.end():] self.dump_attr(pentry, m.group(1)) elif pentry.text: self.dump_attr(pentry, pentry.text) else: m = _parameter_rx.match(line) if not m: raise LaTeXFormatError( "could not extract parameter %s for %s: %s" % (pentry.name, macroname, `line[:100]`)) self.dump_attr(pentry, m.group(1)) line = line[m.end():] elif pentry.type == "child": if pentry.optional: m = _optional_rx.match(line) if m: line = line[m.end():] if entry.outputname and not opened: opened = 1 self.write("(%s\n" % entry.outputname) stack.append(macroname) stack.append(pentry.name) self.write("(%s\n" % pentry.name) self.write("-%s\n" % encode(m.group(1))) self.write(")%s\n" % pentry.name) stack.pop() else: if entry.outputname and not opened: opened = 1 self.write("(%s\n" % entry.outputname) stack.append(entry.name) self.write("(%s\n" % pentry.name) stack.append(pentry.name) self.line = skip_white(line)[1:] line = self.subconvert( "}", len(stack) + depth + 1)[1:] self.write(")%s\n" % stack.pop()) elif pentry.type == "content": if pentry.implied: implied_content = 1 else: if entry.outputname and not opened: opened = 1 self.write("(%s\n" % entry.outputname) stack.append(entry.name) line = skip_white(line) if line[0] != "{": raise LaTeXFormatError( "missing content for " + macroname) self.line = line[1:] line = self.subconvert("}", len(stack) + depth + 1) if line and line[0] == "}": line = line[1:] elif pentry.type == "text": if pentry.text: if entry.outputname and not opened: opened = 1 stack.append(entry.name) self.write("(%s\n" % entry.outputname) self.write("-%s\n" % encode(pentry.text)) if entry.outputname: if not opened: self.write("(%s\n" % entry.outputname) stack.append(entry.name) if not implied_content: self.write(")%s\n" % entry.outputname) stack.pop() self.pop_output() continue if line[0] == endchar and not stack: self.line = line[1:] return self.line if line[0] == "}": macroname = stack[-1] if macroname: conversion = self.table.get(macroname) if conversion.outputname: self.write(")%s\n" % conversion.outputname) del stack[-1] line = line[1:] continue if line[0] == "{": stack.append("") line = line[1:] continue if line[0] == "\\" and line[1] in ESCAPED_CHARS: self.write("-%s\n" % encode(line[1])) line = line[2:] continue if line[:2] == r"\\": self.write("(BREAK\n)BREAK\n") line = line[2:] continue m = _text_rx.match(line) if m: text = encode(m.group()) self.write("-%s\n" % text) line = line[m.end():] continue if line[0] == "]": self.write("-]\n") line = line[1:] continue extra = "" if len(line) > 100: extra = "..." raise LaTeXFormatError("could not identify markup: %s%s" % (`line[:100]`, extra)) while stack: entry = self.get_entry(stack[-1]) if entry.closes: self.write(")%s\n-%s\n" % (entry.outputname, encode("\n"))) del stack[-1] else: break if stack: raise LaTeXFormatError("elements remain on stack: " + string.join(stack, ", ")) def start_macro(self, name): conversion = self.get_entry(name) parameters = conversion.parameters optional = parameters and parameters[0].optional return parameters, optional, conversion.empty, conversion.environment def get_entry(self, name): entry = self.table.get(name) if entry is None: self.err_write("get_entry(%s) failing; building default entry!" % `name`) entry = TableEntry(name) entry.has_content = 1 entry.parameters.append(Parameter("content")) self.table[name] = entry return entry def get_env_entry(self, name): entry = self.table.get(name) if entry is None: entry = TableEntry(name, 1) entry.has_content = 1 entry.parameters.append(Parameter("content")) entry.parameters[-1].implied = 1 self.table[name] = entry elif not entry.environment: raise LaTeXFormatError( name + " is defined as a macro; expected environment") return entry def dump_attr(self, pentry, value): if not (pentry.name and value): return if _token_rx.match(value): dtype = "TOKEN" else: dtype = "CDATA" self.write("A%s %s %s\n" % (pentry.name, dtype, encode(value))) def old_convert(ifp, ofp, table={}, discards=(), autoclosing=()): c = Conversion(ifp, ofp, table, discards, autoclosing) try: c.convert() except IOError, (err, msg): if err != errno.EPIPE: raise
7,455
def skip_white(line): while line and line[0] in " %\n\t": line = string.lstrip(line[1:]) return line
def skip_white(line): while line and line[0] in " %\n\t\r": line = string.lstrip(line[1:]) return line
7,456
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
def main(): global DEBUG convert = new_convert newstyle = 1 opts, args = getopt.getopt(sys.argv[1:], "Dn", ["debug", "new"]) for opt, arg in opts: if opt in ("-n", "--new"): convert = new_convert newstyle = 1 elif opt in ("-o", "--old"): convert = old_convert newstyle = 0 elif opt in ("-D", "--debug"): DEBUG = DEBUG + 1 if len(args) == 0: ifp = sys.stdin ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
7,457
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(args) == 1: ifp = open(args) ofp = sys.stdout elif len(args) == 2: ifp = open(args[0]) ofp = open(args[1], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
7,458
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) table = { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
7,459
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
7,460
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
7,461
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), }, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
def main(): if len(sys.argv) == 2: ifp = open(sys.argv[1]) ofp = sys.stdout elif len(sys.argv) == 3: ifp = open(sys.argv[1]) ofp = open(sys.argv[2], "w") else: usage() sys.exit(2) convert(ifp, ofp, { # entries have the form: # name: ([attribute names], is1stOptional, isEmpty, isEnv, nocontent) # attribute names can be: # "string" -- normal attribute # ("string",) -- sub-element with content of macro; like for \section # ["string"] -- sub-element "appendix": ([], 0, 1, 0, 0), "bifuncindex": (["name"], 0, 1, 0, 0), "catcode": ([], 0, 1, 0, 0), "cfuncdesc": (["type", "name", ("args",)], 0, 0, 1, 0), "chapter": ([("title",)], 0, 0, 0, 0), "chapter*": ([("title",)], 0, 0, 0, 0), "classdesc": (["name", ("args",)], 0, 0, 1, 0), "ctypedesc": (["name"], 0, 0, 1, 0), "cvardesc": (["type", "name"], 0, 0, 1, 0), "datadesc": (["name"], 0, 0, 1, 0), "declaremodule": (["id", "type", "name"], 1, 1, 0, 0), "deprecated": (["release"], 0, 0, 0, 0), "documentclass": (["classname"], 0, 1, 0, 0), "excdesc": (["name"], 0, 0, 1, 0), "funcdesc": (["name", ("args",)], 0, 0, 1, 0), "funcdescni": (["name", ("args",)], 0, 0, 1, 0), "funcline": (["name"], 0, 0, 0, 0), "funclineni": (["name"], 0, 0, 0, 0), "geq": ([], 0, 1, 0, 0), "hline": ([], 0, 1, 0, 0), "include": (["source"], 0, 1, 0, 0), "indexii": (["ie1", "ie2"], 0, 1, 0, 0), "indexiii": (["ie1", "ie2", "ie3"], 0, 1, 0, 0), "indexiv": (["ie1", "ie2", "ie3", "ie4"], 0, 1, 0, 0), "indexname": ([], 0, 0, 0, 0), "input": (["source"], 0, 1, 0, 0), "item": ([("leader",)], 1, 0, 0, 0), "label": (["id"], 0, 1, 0, 0), "labelwidth": ([], 0, 1, 0, 0), "large": ([], 0, 1, 0, 0), "LaTeX": ([], 0, 1, 0, 0), "leftmargin": ([], 0, 1, 0, 0), "leq": ([], 0, 1, 0, 0), "lineii": ([["entry"], ["entry"]], 0, 0, 0, 1), "lineiii": ([["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "lineiv": ([["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 0, 1), "localmoduletable": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "manpage": (["name", "section"], 0, 1, 0, 0), "memberdesc": (["class", "name"], 1, 0, 1, 0), "methoddesc": (["class", "name", ("args",)], 1, 0, 1, 0), "methoddescni": (["class", "name", ("args",)], 1, 0, 1, 0), "methodline": (["class", "name"], 1, 0, 0, 0), "methodlineni": (["class", "name"], 1, 0, 0, 0), "moduleauthor": (["name", "email"], 0, 1, 0, 0), "opcodedesc": (["name", "var"], 0, 0, 1, 0), "par": ([], 0, 1, 0, 0), "paragraph": ([("title",)], 0, 0, 0, 0), "refbimodindex": (["name"], 0, 1, 0, 0), "refexmodindex": (["name"], 0, 1, 0, 0), "refmodindex": (["name"], 0, 1, 0, 0), "refstmodindex": (["name"], 0, 1, 0, 0), "refmodule": (["ref"], 1, 0, 0, 0), "renewcommand": (["macro"], 0, 0, 0, 0), "rfc": (["num"], 0, 1, 0, 0), "section": ([("title",)], 0, 0, 0, 0), "sectionauthor": (["name", "email"], 0, 1, 0, 0), "seemodule": (["ref", "name"], 1, 0, 0, 0), "stindex": (["type"], 0, 1, 0, 0), "subparagraph": ([("title",)], 0, 0, 0, 0), "subsection": ([("title",)], 0, 0, 0, 0), "subsubsection": ([("title",)], 0, 0, 0, 0), "list": (["bullet", "init"], 0, 0, 1, 0), "tableii": (["colspec", "style", ["entry"], ["entry"]], 0, 0, 1, 0), "tableiii": (["colspec", "style", ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "tableiv": (["colspec", "style", ["entry"], ["entry"], ["entry"], ["entry"]], 0, 0, 1, 0), "version": ([], 0, 1, 0, 0), "versionadded": (["version"], 0, 1, 0, 0), "versionchanged": (["version"], 0, 1, 0, 0), "withsubitem": (["text"], 0, 0, 0, 0), # "ABC": ([], 0, 1, 0, 0), "ASCII": ([], 0, 1, 0, 0), "C": ([], 0, 1, 0, 0), "Cpp": ([], 0, 1, 0, 0), "EOF": ([], 0, 1, 0, 0), "e": ([], 0, 1, 0, 0), "ldots": ([], 0, 1, 0, 0), "NULL": ([], 0, 1, 0, 0), "POSIX": ([], 0, 1, 0, 0), "UNIX": ([], 0, 1, 0, 0), # # Things that will actually be going away! # "fi": ([], 0, 1, 0, 0), "ifhtml": ([], 0, 1, 0, 0), "makeindex": ([], 0, 1, 0, 0), "makemodindex": ([], 0, 1, 0, 0), "maketitle": ([], 0, 1, 0, 0), "noindent": ([], 0, 1, 0, 0), "protect": ([], 0, 1, 0, 0), "tableofcontents": ([], 0, 1, 0, 0), } if newstyle: table = load_table(open(os.path.join(sys.path[0], 'conversion.xml'))) convert(ifp, ofp, table, discards=["fi", "ifhtml", "makeindex", "makemodindex", "maketitle", "noindent", "tableofcontents"], autoclosing=["chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", ])
7,462
def test_main(): test.test_support.run_unittest(XrangeTest)
def test_main(): test.test_support.run_unittest(BytesTest)
7,463
def __init__(self, imgtype, name=None, cnf={}, master=None, **kw): self.name = None if not master: master = _default_root if not master: raise RuntimeError, 'Too early to create image' self.tk = master.tk if not name: name = `id(self)` # The following is needed for systems where id(x) # can return a negative number, such as Linux/m68k: if name[0] == '-': name = '_' + name[1:] if kw and cnf: cnf = _cnfmerge((cnf, kw)) elif kw: cnf = kw options = () for k, v in cnf.items(): if callable(v): v = self._register(v) options = options + ('-'+k, v) self.tk.call(('image', 'create', imgtype, name,) + options) self.name = name
def __init__(self, imgtype, name=None, cnf={}, master=None, **kw): self.name = None if not master: master = _default_root if not master: raise RuntimeError, 'Too early to create image' self.tk = master.tk if not name: Image._last_id += 1 name = "pyimage" +`Image._last_id` # The following is needed for systems where id(x) # can return a negative number, such as Linux/m68k: if name[0] == '-': name = '_' + name[1:] if kw and cnf: cnf = _cnfmerge((cnf, kw)) elif kw: cnf = kw options = () for k, v in cnf.items(): if callable(v): v = self._register(v) options = options + ('-'+k, v) self.tk.call(('image', 'create', imgtype, name,) + options) self.name = name
7,464
def strftest(now): if verbose: print "strftime test for", time.ctime(now) nowsecs = int(now) gmt = time.gmtime(now) now = time.localtime(now) if now[3] < 12: ampm='AM' else: ampm='PM' jan1 = time.localtime(time.mktime((now[0], 1, 1) + (0,)*6)) if now[8]: tz = time.tzname[1] else: tz = time.tzname[0] if now[3] > 12: clock12 = now[3] - 12 elif now[3] > 0: clock12 = now[3] else: clock12 = 12 expectations = ( ('%A', calendar.day_name[now[6]], 'full weekday name'), ('%a', calendar.day_abbr[now[6]], 'abbreviated weekday name'), ('%B', calendar.month_name[now[1]], 'full month name'), ('%b', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%h', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%c', fixasctime(time.asctime(now)), 'near-asctime() format'), ('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'), ('%d', '%02d' % now[2], 'day of month as number (00-31)'), ('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'), ('%H', '%02d' % now[3], 'hour (00-23)'), ('%I', '%02d' % clock12, 'hour (01-12)'), ('%j', '%03d' % now[7], 'julian day (001-366)'), ('%M', '%02d' % now[4], 'minute, (00-59)'), ('%m', '%02d' % now[1], 'month as number (01-12)'), ('%p', ampm, 'AM or PM as appropriate'), ('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'), ('%r', '%02d:%02d:%02d %s' % (clock12, now[4], now[5], ampm), '%I:%M:%S %p'), ('%S', '%02d' % now[5], 'seconds of current time (00-60)'), ('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%U', '%02d' % ((now[7] + jan1[6])/7), 'week number of the year (Sun 1st)'), ('%W', '%02d' % ((now[7] + (jan1[6] - 1)%7)/7), 'week number of the year (Mon 1st)'), ('%w', '%d' % ((1+now[6]) % 7), 'weekday as a number (Sun 1st)'), ('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), '%m/%d/%y %H:%M:%S'), ('%Y', '%d' % now[0], 'year with century'), ('%y', '%02d' % (now[0]%100), 'year without century'), ('%Z', tz, 'time zone name'), ('%%', '%', 'single percent sign'), ) nonstandard_expectations = ( ('%C', '%02d' % (now[0]/100), 'century'), # This is for IRIX; on Solaris, %C yields date(1) format. # Tough. ('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'), ('%s', '%d' % nowsecs, 'seconds since the Epoch in UCT'), ('%3y', '%03d' % (now[0]%100), 'year without century rendered using fieldwidth'), ('%n', '\n', 'newline character'), ('%t', '\t', 'tab character'), ) if verbose: print "Strftime test, platform: %s, Python version: %s" % \ (sys.platform, string.split(sys.version)[0]) for e in expectations: try: result = time.strftime(e[0], now) except ValueError, error: print "Standard '%s' format gave error:" % e[0], error continue if result == e[1]: continue if result[0] == '%': print "Does not support standard '%s' format (%s)" % (e[0], e[2]) else: print "Conflict for %s (%s):" % (e[0], e[2]) print " Expected %s, but got %s" % (e[1], result) for e in nonstandard_expectations: try: result = time.strftime(e[0], now) except ValueError, result: if verbose: print "Error for nonstandard '%s' format (%s): %s" % \ (e[0], e[2], str(error)) continue if result == e[1]: if verbose: print "Supports nonstandard '%s' format (%s)" % (e[0], e[2]) elif result[0] == '%': if verbose: print "Does not appear to support '%s' format (%s)" % (e[0], e[2]) else: if verbose: print "Conflict for nonstandard '%s' format (%s):" % (e[0], e[2]) print " Expected %s, but got %s" % (e[1], result)
def strftest(now): if verbose: print "strftime test for", time.ctime(now) nowsecs = int(now) gmt = time.gmtime(now) now = time.localtime(now) if now[3] < 12: ampm='AM' else: ampm='PM' jan1 = time.localtime(time.mktime((now[0], 1, 1) + (0,)*6)) if now[8]: tz = time.tzname[1] else: tz = time.tzname[0] if now[3] > 12: clock12 = now[3] - 12 elif now[3] > 0: clock12 = now[3] else: clock12 = 12 expectations = ( ('%A', calendar.day_name[now[6]], 'full weekday name'), ('%a', calendar.day_abbr[now[6]], 'abbreviated weekday name'), ('%B', calendar.month_name[now[1]], 'full month name'), ('%b', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%h', calendar.month_abbr[now[1]], 'abbreviated month name'), ('%c', fixasctime(time.asctime(now)), 'near-asctime() format'), ('%D', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), 'mm/dd/yy'), ('%d', '%02d' % now[2], 'day of month as number (00-31)'), ('%e', '%2d' % now[2], 'day of month as number, blank padded ( 0-31)'), ('%H', '%02d' % now[3], 'hour (00-23)'), ('%I', '%02d' % clock12, 'hour (01-12)'), ('%j', '%03d' % now[7], 'julian day (001-366)'), ('%M', '%02d' % now[4], 'minute, (00-59)'), ('%m', '%02d' % now[1], 'month as number (01-12)'), ('%p', ampm, 'AM or PM as appropriate'), ('%R', '%02d:%02d' % (now[3], now[4]), '%H:%M'), ('%r', '%02d:%02d:%02d %s' % (clock12, now[4], now[5], ampm), '%I:%M:%S %p'), ('%S', '%02d' % now[5], 'seconds of current time (00-60)'), ('%T', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%X', '%02d:%02d:%02d' % (now[3], now[4], now[5]), '%H:%M:%S'), ('%U', '%02d' % ((now[7] + jan1[6])/7), 'week number of the year (Sun 1st)'), ('%W', '%02d' % ((now[7] + (jan1[6] - 1)%7)/7), 'week number of the year (Mon 1st)'), ('%w', '%d' % ((1+now[6]) % 7), 'weekday as a number (Sun 1st)'), ('%x', '%02d/%02d/%02d' % (now[1], now[2], (now[0]%100)), '%m/%d/%y %H:%M:%S'), ('%Y', '%d' % now[0], 'year with century'), ('%y', '%02d' % (now[0]%100), 'year without century'), ('%Z', tz, 'time zone name'), ('%%', '%', 'single percent sign'), ) nonstandard_expectations = ( ('%C', '%02d' % (now[0]/100), 'century'), # This is for IRIX; on Solaris, %C yields date(1) format. # Tough. ('%k', '%2d' % now[3], 'hour, blank padded ( 0-23)'), ('%s', '%d' % nowsecs, 'seconds since the Epoch in UCT'), ('%3y', '%03d' % (now[0]%100), 'year without century rendered using fieldwidth'), ('%n', '\n', 'newline character'), ('%t', '\t', 'tab character'), ) if verbose: print "Strftime test, platform: %s, Python version: %s" % \ (sys.platform, string.split(sys.version)[0]) for e in expectations: try: result = time.strftime(e[0], now) except ValueError, error: print "Standard '%s' format gave error:" % e[0], error continue if result == e[1]: continue if result[0] == '%': print "Does not support standard '%s' format (%s)" % (e[0], e[2]) else: print "Conflict for %s (%s):" % (e[0], e[2]) print " Expected %s, but got %s" % (e[1], result) for e in nonstandard_expectations: try: result = time.strftime(e[0], now) except ValueError, result: if verbose: print "Error for nonstandard '%s' format (%s): %s" % \ (e[0], e[2], str(result)) continue if result == e[1]: if verbose: print "Supports nonstandard '%s' format (%s)" % (e[0], e[2]) elif result[0] == '%': if verbose: print "Does not appear to support '%s' format (%s)" % (e[0], e[2]) else: if verbose: print "Conflict for nonstandard '%s' format (%s):" % (e[0], e[2]) print " Expected %s, but got %s" % (e[1], result)
7,465
def nti(s): """Convert a number field to a python number. """ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0200): n = int(s.rstrip(NUL) or "0", 8) else: n = 0L for i in xrange(len(s) - 1): n <<= 8 n += ord(s[i + 1]) return n
def nti(s): """Convert a number field to a python number. """ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0200): n = int(s.rstrip(NUL + " ") or "0", 8) else: n = 0L for i in xrange(len(s) - 1): n <<= 8 n += ord(s[i + 1]) return n
7,466
def __init__(self, host = '', port = 0, local_hostname = None): """Initialize a new instance.
def __init__(self, host = '', port = 0, local_hostname = None): """Initialize a new instance.
7,467
def __init__(self, parent, title = None):
def __init__(self, parent, title = None):
7,468
def list(self, which=None): """Request listing, return result. Result is in form ['response', ['mesg_num octets', ...]].
def list(self, msg=None): """Request listing, return result. Result is in form ['response', ['mesg_num octets', ...]].
7,469
def list(self, which=None): """Request listing, return result. Result is in form ['response', ['mesg_num octets', ...]].
def list(self, which=None): """Request listing, return result. Result is in form ['response', ['mesg_num octets', ...]].
7,470
def list(self, which=None): """Request listing, return result. Result is in form ['response', ['mesg_num octets', ...]].
def list(self, which=None): """Request listing, return result. Result is in form ['response', ['mesg_num octets', ...]].
7,471
def __init__(self, strm=None): """ Initialize the handler.
def __init__(self, strm=None): """ Initialize the handler.
7,472
def has_key(self, key): try: value = self[key] except KeyError: return False return True
def has_key(self, key): try: value = self[key] except KeyError: return False return True
7,473
def iteritems(self): for k in self: yield (k, self[k])
def iteritems(self): for k in self: yield (k, self[k])
7,474
def get_file_list (self): """Figure out the list of files to include in the source distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options and the state of the filesystem. """
def get_file_list (self): """Figure out the list of files to include in the source distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options and the state of the filesystem. """
7,475
def add_defaults (self): """Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional. """
def add_defaults (self): """Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional. """
7,476
def redirect_request(self, req, fp, code, msg, headers, newurl): """Return a Request or None in response to a redirect.
def redirect_request(self, req, fp, code, msg, headers, newurl): """Return a Request or None in response to a redirect.
7,477
def http_error_302(self, req, fp, code, msg, headers): if 'location' in headers: newurl = headers['location'] elif 'uri' in headers: newurl = headers['uri'] else: return newurl = urlparse.urljoin(req.get_full_url(), newurl)
def http_error_302(self, req, fp, code, msg, headers): if 'location' in headers: newurl = headers['location'] elif 'uri' in headers: newurl = headers['uri'] else: return newurl = urlparse.urljoin(req.get_full_url(), newurl)
7,478
def http_error_302(self, req, fp, code, msg, headers): if 'location' in headers: newurl = headers['location'] elif 'uri' in headers: newurl = headers['uri'] else: return newurl = urlparse.urljoin(req.get_full_url(), newurl)
def http_error_302(self, req, fp, code, msg, headers): if 'location' in headers: newurl = headers['location'] elif 'uri' in headers: newurl = headers['uri'] else: return newurl = urlparse.urljoin(req.get_full_url(), newurl)
7,479
def powtest(type): if type != float: print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if pow(type(i), 0) != 1: raise ValueError, 'pow('+str(i)+',0) != 1' if pow(type(i), 1) != type(i): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if pow(type(0), 1) != type(0): raise ValueError, 'pow(0,'+str(i)+') != 0' if pow(type(1), 1) != type(1): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if pow(type(i), 3) != i*i*i: raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2 = 1 for i in range(0,31): if pow(2, i) != pow2: raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if i != 30 : pow2 = pow2*2 for othertype in int, long: for i in range(-10, 0) + range(1, 10): ii = type(i) for j in range(1, 11): jj = -othertype(j) try: pow(ii, jj) except ValueError: raise ValueError, "pow(%s, %s) failed" % (ii, jj) for othertype in int, long, float: for i in range(1, 100): zero = type(0) exp = -othertype(i/10.0) if exp == 0: continue try: pow(zero, exp) except ZeroDivisionError: pass # taking zero to any negative exponent should fail else: raise ValueError, "pow(%s, %s) did not fail" % (zero, exp) print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if type == float: il = 1 compare = test_support.fcmp elif type == int: jl = 0 elif type == long: jl, jh = 0, 15 for i in range(il, ih+1): for j in range(jl, jh+1): for k in range(kl, kh+1): if k != 0: if type == float or j < 0: try: pow(type(i),j,k) except TypeError: pass else: raise ValueError, "expected TypeError from " + \ "pow%r" % ((type(i), j, k),) continue if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(PowTest)) test.test_support.run_suite(suite) for i in range(-100, 100): if pow(type(i), 3) != i*i*i: raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2 = 1 for i in range(0,31): if pow(2, i) != pow2: raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if i != 30 : pow2 = pow2*2 for othertype in int, long: for i in range(-10, 0) + range(1, 10): ii = type(i) for j in range(1, 11): jj = -othertype(j) try: pow(ii, jj) except ValueError: raise ValueError, "pow(%s, %s) failed" % (ii, jj) for othertype in int, long, float: for i in range(1, 100): zero = type(0) exp = -othertype(i/10.0) if exp == 0: continue try: pow(zero, exp) except ZeroDivisionError: pass # taking zero to any negative exponent should fail else: raise ValueError, "pow(%s, %s) did not fail" % (zero, exp) print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if type == float: il = 1 compare = test_support.fcmp elif type == int: jl = 0 elif type == long: jl, jh = 0, 15 for i in range(il, ih+1): for j in range(jl, jh+1): for k in range(kl, kh+1): if k != 0: if type == float or j < 0: try: pow(type(i),j,k) except TypeError: pass else: raise ValueError, "expected TypeError from " + \ "pow%r" % ((type(i), j, k),) continue if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
7,480
def powtest(type): if type != float: print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if pow(type(i), 0) != 1: raise ValueError, 'pow('+str(i)+',0) != 1' if pow(type(i), 1) != type(i): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if pow(type(0), 1) != type(0): raise ValueError, 'pow(0,'+str(i)+') != 0' if pow(type(1), 1) != type(1): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if pow(type(i), 3) != i*i*i: raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2 = 1 for i in range(0,31): if pow(2, i) != pow2: raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if i != 30 : pow2 = pow2*2 for othertype in int, long: for i in range(-10, 0) + range(1, 10): ii = type(i) for j in range(1, 11): jj = -othertype(j) try: pow(ii, jj) except ValueError: raise ValueError, "pow(%s, %s) failed" % (ii, jj) for othertype in int, long, float: for i in range(1, 100): zero = type(0) exp = -othertype(i/10.0) if exp == 0: continue try: pow(zero, exp) except ZeroDivisionError: pass # taking zero to any negative exponent should fail else: raise ValueError, "pow(%s, %s) did not fail" % (zero, exp) print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if type == float: il = 1 compare = test_support.fcmp elif type == int: jl = 0 elif type == long: jl, jh = 0, 15 for i in range(il, ih+1): for j in range(jl, jh+1): for k in range(kl, kh+1): if k != 0: if type == float or j < 0: try: pow(type(i),j,k) except TypeError: pass else: raise ValueError, "expected TypeError from " + \ "pow%r" % ((type(i), j, k),) continue if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
def powtest(type): if type != float: print " Testing 2-argument pow() function..." for i in range(-1000, 1000): if pow(type(i), 0) != 1: raise ValueError, 'pow('+str(i)+',0) != 1' if pow(type(i), 1) != type(i): raise ValueError, 'pow('+str(i)+',1) != '+str(i) if pow(type(0), 1) != type(0): raise ValueError, 'pow(0,'+str(i)+') != 0' if pow(type(1), 1) != type(1): raise ValueError, 'pow(1,'+str(i)+') != 1' for i in range(-100, 100): if pow(type(i), 3) != i*i*i: raise ValueError, 'pow('+str(i)+',3) != '+str(i*i*i) pow2 = 1 for i in range(0,31): if pow(2, i) != pow2: raise ValueError, 'pow(2,'+str(i)+') != '+str(pow2) if i != 30 : pow2 = pow2*2 for othertype in int, long: for i in range(-10, 0) + range(1, 10): ii = type(i) for j in range(1, 11): jj = -othertype(j) try: pow(ii, jj) except ValueError: raise ValueError, "pow(%s, %s) failed" % (ii, jj) for othertype in int, long, float: for i in range(1, 100): zero = type(0) exp = -othertype(i/10.0) if exp == 0: continue try: pow(zero, exp) except ZeroDivisionError: pass # taking zero to any negative exponent should fail else: raise ValueError, "pow(%s, %s) did not fail" % (zero, exp) print " Testing 3-argument pow() function..." il, ih = -20, 20 jl, jh = -5, 5 kl, kh = -10, 10 compare = cmp if type == float: il = 1 compare = test_support.fcmp elif type == int: jl = 0 elif type == long: jl, jh = 0, 15 for i in range(il, ih+1): for j in range(jl, jh+1): for k in range(kl, kh+1): if k != 0: if type == float or j < 0: try: pow(type(i),j,k) except TypeError: pass else: raise ValueError, "expected TypeError from " + \ "pow%r" % ((type(i), j, k),) continue if compare(pow(type(i),j,k), pow(type(i),j)% type(k)): raise ValueError, "pow(" +str(i)+ "," +str(j)+ \ "," +str(k)+ ") != pow(" +str(i)+ "," + \ str(j)+ ") % " +str(k)
7,481
def record_sub_info(match_object,sub_info=sub_info): sub_info.append([match_object.group(1)[0],match_object.span()]) return match_object.group(1)
def record_sub_info(match_object,sub_info=sub_info): sub_info.append([match_object.group(1)[0],match_object.span()]) return match_object.group(1)
7,482
def __str__(self): if self.filename: return '[Errno %d] %s: %s' % (self.errno, self.strerror, self.filename) elif self.errno and self.strerror: return '[Errno %d] %s' % (self.errno, self.strerror) else: return StandardError.__str__(self)
def __str__(self): if self.filename: return '[Errno %s] %s: %s' % (self.errno, self.strerror, self.filename) elif self.errno and self.strerror: return '[Errno %d] %s' % (self.errno, self.strerror) else: return StandardError.__str__(self)
7,483
def __str__(self): if self.filename: return '[Errno %d] %s: %s' % (self.errno, self.strerror, self.filename) elif self.errno and self.strerror: return '[Errno %d] %s' % (self.errno, self.strerror) else: return StandardError.__str__(self)
def __str__(self): if self.filename: return '[Errno %d] %s: %s' % (self.errno, self.strerror, self.filename) elif self.errno and self.strerror: return '[Errno %s] %s' % (self.errno, self.strerror) else: return StandardError.__str__(self)
7,484
def _readmodule(module, path, inpackage=None): '''Do the hard work for readmodule[_ex].''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = _readmodule(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return _readmodule(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict stack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if tokentype == DEDENT: lineno, thisindent = start # close nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] elif token == 'def': lineno, thisindent = start # close previous nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error if stack: cur_class = stack[-1][0] if isinstance(cur_class, Class): # it's a method cur_class._addmethod(meth_name, lineno) # else it's a nested def else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) stack.append((None, thisindent)) # Marker for nested fns elif token == 'class': lineno, thisindent = start # close previous nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) super = [] if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(fullmodule, class_name, inherit, file, lineno) if not stack: dict[class_name] = cur_class stack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: _readmodule(mod, path) else: try: _readmodule(mod, path, inpackage) except ImportError: _readmodule(mod, []) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = _readmodule(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # don't add names that start with _ for n in d: if n[0] != '_': dict[n] = d[n] except StopIteration: pass f.close() return dict
def _readmodule(module, path, inpackage=None): '''Do the hard work for readmodule[_ex].''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) elif tokentype in (NAME, OP) and level == 1: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = _readmodule(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return _readmodule(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) elif tokentype in (NAME, OP) and level == 1: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict stack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if tokentype == DEDENT: lineno, thisindent = start # close nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] elif token == 'def': lineno, thisindent = start # close previous nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error if stack: cur_class = stack[-1][0] if isinstance(cur_class, Class): # it's a method cur_class._addmethod(meth_name, lineno) # else it's a nested def elif tokentype in (NAME, OP) and level == 1: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) stack.append((None, thisindent)) # Marker for nested fns elif token == 'class': lineno, thisindent = start # close previous nested classes and defs while stack and stack[-1][1] >= thisindent: del stack[-1] tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] elif tokentype in (NAME, OP) and level == 1: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) super = [] if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass elif tokentype in (NAME, OP) and level == 1: super.append(token) inherit = names cur_class = Class(fullmodule, class_name, inherit, file, lineno) if not stack: dict[class_name] = cur_class stack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: _readmodule(mod, path) elif tokentype in (NAME, OP) and level == 1: try: _readmodule(mod, path, inpackage) except ImportError: _readmodule(mod, []) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = _readmodule(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # don't add names that start with _ for n in d: if n[0] != '_': dict[n] = d[n] except StopIteration: pass f.close() return dict
7,485
def __init__(self, host = '', port = IMAP4_PORT): self.host = host self.port = port self.debug = Debug self.state = 'LOGOUT' self.literal = None # A literal argument to a command self.tagged_commands = {} # Tagged commands awaiting response self.untagged_responses = {} # {typ: [data, ...], ...} self.continuation_response = '' # Last continuation response self.tagnum = 0
def __init__(self, host = '', port = IMAP4_PORT): self.host = host self.port = port self.debug = Debug self.state = 'LOGOUT' self.literal = None # A literal argument to a command self.tagged_commands = {} # Tagged commands awaiting response self.untagged_responses = {} # {typ: [data, ...], ...} self.continuation_response = '' # Last continuation response self.tagnum = 0
7,486
def __init__(self, host = '', port = IMAP4_PORT): self.host = host self.port = port self.debug = Debug self.state = 'LOGOUT' self.literal = None # A literal argument to a command self.tagged_commands = {} # Tagged commands awaiting response self.untagged_responses = {} # {typ: [data, ...], ...} self.continuation_response = '' # Last continuation response self.tagnum = 0
def __init__(self, host = '', port = IMAP4_PORT): self.host = host self.port = port self.debug = Debug self.state = 'LOGOUT' self.literal = None # A literal argument to a command self.tagged_commands = {} # Tagged commands awaiting response self.untagged_responses = {} # {typ: [data, ...], ...} self.continuation_response = '' # Last continuation response self.tagnum = 0
7,487
def __getattr__(self, attr): """Allow UPPERCASE variants of all following IMAP4 commands.""" if Commands.has_key(attr): return eval("self.%s" % string.lower(attr)) raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
def __getattr__(self, attr): """Allow UPPERCASE variants of all following IMAP4 commands.""" if Commands.has_key(attr): return eval("self.%s" % string.lower(attr)) raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
7,488
def authenticate(self, mechanism, authobject): """Authenticate command - requires response processing.
def authenticate(self, mechanism, authobject): """Authenticate command - requires response processing.
7,489
def close(self): """Close currently selected mailbox.
def close(self): """Close currently selected mailbox.
7,490
def expunge(self): """Permanently remove deleted items from selected mailbox.
def expunge(self): """Permanently remove deleted items from selected mailbox.
7,491
def fetch(self, message_set, message_parts): """Fetch (parts of) messages.
def fetch(self, message_set, message_parts): """Fetch (parts of) messages.
7,492
def list(self, directory='""', pattern='*'): """List mailbox names in directory matching pattern.
def list(self, directory='""', pattern='*'): """List mailbox names in directory matching pattern.
7,493
def login(self, user, password): """Identify client using plaintext password.
def login(self, user, password): """Identify client using plaintext password.
7,494
def logout(self): """Shutdown connection to server.
def logout(self): """Shutdown connection to server.
7,495
def lsub(self, directory='""', pattern='*'): """List 'subscribed' mailbox names in directory matching pattern.
def lsub(self, directory='""', pattern='*'): """List 'subscribed' mailbox names in directory matching pattern.
7,496
def noop(self): """Send NOOP command.
def noop(self): """Send NOOP command.
7,497
def partial(self, message_num, message_part, start, length): """Fetch truncated part of a message.
def partial(self, message_num, message_part, start, length): """Fetch truncated part of a message.
7,498
def rename(self, oldmailbox, newmailbox): """Rename old mailbox name to new.
def rename(self, oldmailbox, newmailbox): """Rename old mailbox name to new.
7,499