rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
elif node_check is map:
elif node_check is dict:
def add_path_resolver(cls, tag, path, kind=None): if not 'yaml_path_resolvers' in cls.__dict__: cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy() new_path = [] for element in path: if isinstance(element, (list, tuple)): if len(element) == 2: node_check, index_check = element elif len(element) == 1: node_check = element[0] index_check = True else: raise ResolverError("Invalid path element: %s" % element) else: node_check = None index_check = element if node_check is str: node_check = ScalarNode elif node_check is list: node_check = SequenceNode elif node_check is map: node_check = MappingNode elif node_check not in [ScalarNode, SequenceNode, MappingNode] \ and not isinstance(node_check, basestring) \ and node_check is not None: raise ResolverError("Invalid node checker: %s" % node_check) if not isinstance(index_check, (basestring, int)) \ and index_check is not None: raise ResolverError("Invalid index checker: %s" % index_check) new_path.append((node_check, index_check)) if kind is str: kind = ScalarNode elif kind is list: kind = SequenceNode elif kind is map: kind = MappingNode elif kind not in [ScalarNode, SequenceNode, MappingNode] \ and kind is not None: raise ResolverError("Invalid node kind: %s" % kind) cls.yaml_path_resolvers[tuple(new_path), kind] = tag
elif kind is map:
elif kind is dict:
def add_path_resolver(cls, tag, path, kind=None): if not 'yaml_path_resolvers' in cls.__dict__: cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy() new_path = [] for element in path: if isinstance(element, (list, tuple)): if len(element) == 2: node_check, index_check = element elif len(element) == 1: node_check = element[0] index_check = True else: raise ResolverError("Invalid path element: %s" % element) else: node_check = None index_check = element if node_check is str: node_check = ScalarNode elif node_check is list: node_check = SequenceNode elif node_check is map: node_check = MappingNode elif node_check not in [ScalarNode, SequenceNode, MappingNode] \ and not isinstance(node_check, basestring) \ and node_check is not None: raise ResolverError("Invalid node checker: %s" % node_check) if not isinstance(index_check, (basestring, int)) \ and index_check is not None: raise ResolverError("Invalid index checker: %s" % index_check) new_path.append((node_check, index_check)) if kind is str: kind = ScalarNode elif kind is list: kind = SequenceNode elif kind is map: kind = MappingNode elif kind not in [ScalarNode, SequenceNode, MappingNode] \ and kind is not None: raise ResolverError("Invalid node kind: %s" % kind) cls.yaml_path_resolvers[tuple(new_path), kind] = tag
collection_events = None
def parse_node(self, block=False, indentless_sequence=False): if self.check_token(AliasToken): token = self.get_token() event = AliasEvent(token.value, token.start_mark, token.end_mark) self.state = self.states.pop() else: anchor = None tag = None start_mark = end_mark = tag_mark = None if self.check_token(AnchorToken): token = self.get_token() start_mark = token.start_mark end_mark = token.end_mark anchor = token.value if self.check_token(TagToken): token = self.get_token() tag_mark = token.start_mark end_mark = token.end_mark tag = token.value elif self.check_token(TagToken): token = self.get_token() start_mark = tag_mark = token.start_mark end_mark = token.end_mark tag = token.value if self.check_token(AnchorToken): token = self.get_token() end_mark = token.end_mark anchor = token.value if tag is not None and tag != u'!': handle, suffix = tag if handle is not None: if handle not in self.tag_handles: raise ParserError("while parsing a node", start_mark, "found undefined tag handle %r" % handle.encode('utf-8'), tag_mark) tag = self.tag_handles[handle]+suffix else: tag = suffix #if tag == u'!': # raise ParserError("while parsing a node", start_mark, # "found non-specific tag '!'", tag_mark, # "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.") if start_mark is None: start_mark = end_mark = self.peek_token().start_mark event = None collection_events = None implicit = (tag is None or tag == u'!') if indentless_sequence and self.check_token(BlockEntryToken): end_mark = self.peek_token().end_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark) self.state = self.parse_indentless_sequence_entry else: if self.check_token(ScalarToken): token = self.get_token() end_mark = token.end_mark if (token.plain and tag is None) or tag == u'!': implicit = (True, False) elif tag is None: implicit = (False, True) else: implicit = (False, False) event = ScalarEvent(anchor, tag, implicit, token.value, start_mark, end_mark, style=token.style) self.state = self.states.pop() elif self.check_token(FlowSequenceStartToken): end_mark = self.peek_token().end_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=True) self.state = self.parse_flow_sequence_first_entry elif self.check_token(FlowMappingStartToken): end_mark = self.peek_token().end_mark event = MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=True) self.state = self.parse_flow_mapping_first_key elif block and self.check_token(BlockSequenceStartToken): end_mark = self.peek_token().start_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=False) self.state = self.parse_block_sequence_first_entry elif block and self.check_token(BlockMappingStartToken): end_mark = self.peek_token().start_mark event = MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=False) self.state = self.parse_block_mapping_first_key elif anchor is not None or tag is not None: # Empty scalars are allowed even if a tag or an anchor is # specified. event = ScalarEvent(anchor, tag, (implicit, False), u'', start_mark, end_mark) self.state = self.states.pop() else: if block: node = 'block' else: node = 'flow' token = self.peek_token() raise ParserError("while scanning a %s node" % node, start_mark, "expected the node content, but found %r" % token.id, token.start_mark) return event
raise ParserError("while scanning a %s node" % node, start_mark,
raise ParserError("while parsing a %s node" % node, start_mark,
def parse_node(self, block=False, indentless_sequence=False): if self.check_token(AliasToken): token = self.get_token() event = AliasEvent(token.value, token.start_mark, token.end_mark) self.state = self.states.pop() else: anchor = None tag = None start_mark = end_mark = tag_mark = None if self.check_token(AnchorToken): token = self.get_token() start_mark = token.start_mark end_mark = token.end_mark anchor = token.value if self.check_token(TagToken): token = self.get_token() tag_mark = token.start_mark end_mark = token.end_mark tag = token.value elif self.check_token(TagToken): token = self.get_token() start_mark = tag_mark = token.start_mark end_mark = token.end_mark tag = token.value if self.check_token(AnchorToken): token = self.get_token() end_mark = token.end_mark anchor = token.value if tag is not None and tag != u'!': handle, suffix = tag if handle is not None: if handle not in self.tag_handles: raise ParserError("while parsing a node", start_mark, "found undefined tag handle %r" % handle.encode('utf-8'), tag_mark) tag = self.tag_handles[handle]+suffix else: tag = suffix #if tag == u'!': # raise ParserError("while parsing a node", start_mark, # "found non-specific tag '!'", tag_mark, # "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.") if start_mark is None: start_mark = end_mark = self.peek_token().start_mark event = None collection_events = None implicit = (tag is None or tag == u'!') if indentless_sequence and self.check_token(BlockEntryToken): end_mark = self.peek_token().end_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark) self.state = self.parse_indentless_sequence_entry else: if self.check_token(ScalarToken): token = self.get_token() end_mark = token.end_mark if (token.plain and tag is None) or tag == u'!': implicit = (True, False) elif tag is None: implicit = (False, True) else: implicit = (False, False) event = ScalarEvent(anchor, tag, implicit, token.value, start_mark, end_mark, style=token.style) self.state = self.states.pop() elif self.check_token(FlowSequenceStartToken): end_mark = self.peek_token().end_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=True) self.state = self.parse_flow_sequence_first_entry elif self.check_token(FlowMappingStartToken): end_mark = self.peek_token().end_mark event = MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=True) self.state = self.parse_flow_mapping_first_key elif block and self.check_token(BlockSequenceStartToken): end_mark = self.peek_token().start_mark event = SequenceStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=False) self.state = self.parse_block_sequence_first_entry elif block and self.check_token(BlockMappingStartToken): end_mark = self.peek_token().start_mark event = MappingStartEvent(anchor, tag, implicit, start_mark, end_mark, flow_style=False) self.state = self.parse_block_mapping_first_key elif anchor is not None or tag is not None: # Empty scalars are allowed even if a tag or an anchor is # specified. event = ScalarEvent(anchor, tag, (implicit, False), u'', start_mark, end_mark) self.state = self.states.pop() else: if block: node = 'block' else: node = 'flow' token = self.peek_token() raise ParserError("while scanning a %s node" % node, start_mark, "expected the node content, but found %r" % token.id, token.start_mark) return event
raise ParserError("while scanning a block collection", self.marks[-1],
raise ParserError("while parsing a block collection", self.marks[-1],
def parse_block_sequence_entry(self): if self.check_token(BlockEntryToken): token = self.get_token() if not self.check_token(BlockEntryToken, BlockEndToken): self.states.append(self.parse_block_sequence_entry) return self.parse_block_node() else: self.state = self.parse_block_sequence_entry return self.process_empty_scalar(token.end_mark) if not self.check_token(BlockEndToken): token = self.peek_token() raise ParserError("while scanning a block collection", self.marks[-1], "expected <block end>, but found %r" % token.id, token.start_mark) token = self.get_token() event = SequenceEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event
raise ParserError("while scanning a block mapping", self.marks[-1],
raise ParserError("while parsing a block mapping", self.marks[-1],
def parse_block_mapping_key(self): if self.check_token(KeyToken): token = self.get_token() if not self.check_token(KeyToken, ValueToken, BlockEndToken): self.states.append(self.parse_block_mapping_value) return self.parse_block_node_or_indentless_sequence() else: self.state = self.parse_block_mapping_value return self.process_empty_scalar(token.end_mark) if not self.check_token(BlockEndToken): token = self.peek_token() raise ParserError("while scanning a block mapping", self.marks[-1], "expected <block end>, but found %r" % token.id, token.start_mark) token = self.get_token() event = MappingEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event
raise ParserError("while scanning a flow sequence", self.marks[-1],
raise ParserError("while parsing a flow sequence", self.marks[-1],
def parse_flow_sequence_entry(self, first=False): if not self.check_token(FlowSequenceEndToken): if not first: if self.check_token(FlowEntryToken): self.get_token() else: token = self.peek_token() raise ParserError("while scanning a flow sequence", self.marks[-1], "expected ',' or ']', but got %r" % token.id, token.start_mark) if self.check_token(KeyToken): token = self.get_token() event = MappingStartEvent(None, None, True, token.start_mark, token.end_mark, flow_style=True) self.state = self.parse_flow_sequence_entry_mapping_key return event elif not self.check_token(FlowSequenceEndToken): self.states.append(self.parse_flow_sequence_entry) return self.parse_flow_node() token = self.get_token() event = SequenceEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event
token = self.get_token()
token = self.peek_token()
def parse_flow_sequence_entry(self, first=False): if not self.check_token(FlowSequenceEndToken): if not first: if self.check_token(FlowEntryToken): self.get_token() else: token = self.peek_token() raise ParserError("while scanning a flow sequence", self.marks[-1], "expected ',' or ']', but got %r" % token.id, token.start_mark) if self.check_token(KeyToken): token = self.get_token() event = MappingStartEvent(None, None, True, token.start_mark, token.end_mark, flow_style=True) self.state = self.parse_flow_sequence_entry_mapping_key return event elif not self.check_token(FlowSequenceEndToken): self.states.append(self.parse_flow_sequence_entry) return self.parse_flow_node() token = self.get_token() event = SequenceEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event
raise ParserError("while scanning a flow mapping", self.marks[-1],
raise ParserError("while parsing a flow mapping", self.marks[-1],
def parse_flow_mapping_key(self, first=False): if not self.check_token(FlowMappingEndToken): if not first: if self.check_token(FlowEntryToken): self.get_token() else: token = self.peek_token() raise ParserError("while scanning a flow mapping", self.marks[-1], "expected ',' or '}', but got %r" % token.id, token.start_mark) if self.check_token(KeyToken): token = self.get_token() if not self.check_token(ValueToken, FlowEntryToken, FlowMappingEndToken): self.states.append(self.parse_flow_mapping_value) return self.parse_flow_node() else: self.state = self.parse_flow_mapping_value return self.process_empty_scalar(token.end_mark) elif not self.check_token(FlowMappingEndToken): self.states.append(self.parse_flow_mapping_empty_value) return self.parse_flow_node() token = self.get_token() event = MappingEndEvent(token.start_mark, token.end_mark) self.state = self.states.pop() self.marks.pop() return event
parameters = yaml.load_document(config)
parameters = yaml.load(config)
def __init__(self, config): parameters = yaml.load_document(config) self.replaces = parameters['replaces'] self.substitutions = {} for domain, items in [('Token', parameters['tokens']), ('Event', parameters['events'])]: for code in items: name = ''.join([part.capitalize() for part in code.split('-')]+[domain]) cls = getattr(yaml, name) value = items[code] if value: if 'start' in value: self.substitutions[cls, -1] = value['start'] if 'end' in value: self.substitutions[cls, +1] = value['end']
tokens = yaml.parse(input, Parser=iter)
tokens = yaml.scan(input)
def highlight(self, input): if isinstance(input, str): if input.startswith(codecs.BOM_UTF16_LE): input = unicode(input, 'utf-16-le') elif input.startswith(codecs.BOM_UTF16_BE): input = unicode(input, 'utf-16-be') else: input = unicode(input, 'utf-8') tokens = yaml.parse(input, Parser=iter) events = yaml.parse(input) markers = [] number = 0 for token in tokens: number += 1 if token.start_mark.index != token.end_mark.index: cls = token.__class__ if (cls, -1) in self.substitutions: markers.append([token.start_mark.index, +2, number, self.substitutions[cls, -1]]) if (cls, +1) in self.substitutions: markers.append([token.end_mark.index, -2, number, self.substitutions[cls, +1]]) number = 0 for event in events: number += 1 cls = event.__class__ if (cls, -1) in self.substitutions: markers.append([event.start_mark.index, +1, number, self.substitutions[cls, -1]]) if (cls, +1) in self.substitutions: markers.append([event.end_mark.index, -1, number, self.substitutions[cls, +1]]) markers.sort() markers.reverse() chunks = [] position = len(input) for index, weight1, weight2, substitution in markers: if index < position: chunk = input[index:position] for substring, replacement in self.replaces: chunk = chunk.replace(substring, replacement) chunks.append(chunk) position = index chunks.append(substitution) chunks.reverse() result = u''.join(chunks) return result.encode('utf-8')
return float(value)
return sign*float(value)
def construct_yaml_float(self, node): value = str(self.construct_scalar(node)) value = value.replace('_', '') sign = +1 if value[0] == '-': sign = -1 if value[0] in '+-': value = value[1:] if value.lower() == '.inf': return sign*self.inf_value elif value.lower() == '.nan': return self.nan_value elif ':' in value: digits = [float(part) for part in value.split(':')] digits.reverse() base = 1 value = 0.0 for digit in digits: value += digit*base base *= 60 return sign*value else: return float(value)
self.peek(length+1) in u'\0 \t\r\n\x28\u2028\u2029') \
self.peek(length+1) in u'\0 \t\r\n\x85\u2028\u2029') \
def scan_plain(self): # See the specification for details. # We add an additional restriction for the flow context: # plain scalars in the flow context cannot contain ',', ':' and '?'. # We also keep track of the `allow_simple_key` flag here. # Indentation rules are loosed for the flow context. chunks = [] start_mark = self.get_mark() end_mark = start_mark indent = self.indent+1 # We allow zero indentation for scalars, but then we need to check for # document separators at the beginning of the line. #if indent == 0: # indent = 1 spaces = [] while True: length = 0 if self.peek() == u'#': break while True: ch = self.peek(length) if ch in u'\0 \t\r\n\x85\u2028\u2029' \ or (not self.flow_level and ch == u':' and self.peek(length+1) in u'\0 \t\r\n\x28\u2028\u2029') \ or (self.flow_level and ch in u',:?[]{}'): break length += 1 # It's not clear what we should do with ':' in the flow context. if (self.flow_level and ch == u':' and self.peek(length+1) not in u'\0 \t\r\n\x28\u2028\u2029,[]{}'): self.forward(length) raise ScannerError("while scanning a plain scalar", start_mark, "found unexpected ':'", self.get_mark(), "Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details.") if length == 0: break self.allow_simple_key = False chunks.extend(spaces) chunks.append(self.prefix(length)) self.forward(length) end_mark = self.get_mark() spaces = self.scan_plain_spaces(indent, start_mark) if not spaces or self.peek() == u'#' \ or (not self.flow_level and self.column < indent): break return ScalarToken(u''.join(chunks), True, start_mark, end_mark)
and self.peek(length+1) not in u'\0 \t\r\n\x28\u2028\u2029,[]{}'):
and self.peek(length+1) not in u'\0 \t\r\n\x85\u2028\u2029,[]{}'):
def scan_plain(self): # See the specification for details. # We add an additional restriction for the flow context: # plain scalars in the flow context cannot contain ',', ':' and '?'. # We also keep track of the `allow_simple_key` flag here. # Indentation rules are loosed for the flow context. chunks = [] start_mark = self.get_mark() end_mark = start_mark indent = self.indent+1 # We allow zero indentation for scalars, but then we need to check for # document separators at the beginning of the line. #if indent == 0: # indent = 1 spaces = [] while True: length = 0 if self.peek() == u'#': break while True: ch = self.peek(length) if ch in u'\0 \t\r\n\x85\u2028\u2029' \ or (not self.flow_level and ch == u':' and self.peek(length+1) in u'\0 \t\r\n\x28\u2028\u2029') \ or (self.flow_level and ch in u',:?[]{}'): break length += 1 # It's not clear what we should do with ':' in the flow context. if (self.flow_level and ch == u':' and self.peek(length+1) not in u'\0 \t\r\n\x28\u2028\u2029,[]{}'): self.forward(length) raise ScannerError("while scanning a plain scalar", start_mark, "found unexpected ':'", self.get_mark(), "Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details.") if length == 0: break self.allow_simple_key = False chunks.extend(spaces) chunks.append(self.prefix(length)) self.forward(length) end_mark = self.get_mark() spaces = self.scan_plain_spaces(indent, start_mark) if not spaces or self.peek() == u'#' \ or (not self.flow_level and self.column < indent): break return ScalarToken(u''.join(chunks), True, start_mark, end_mark)
prefix = self.peek(4)
def check_document_end(self):
reduce = copy_reg.dispatch_table[cls]
reduce = copy_reg.dispatch_table[cls](data)
def represent_object(self, data): # We use __reduce__ API to save the data. data.__reduce__ returns # a tuple of length 2-5: # (function, args, state, listitems, dictitems)
if not self.flow_level and self.analysis.allow_block:
if (not self.flow_level and not self.simple_key_context and self.analysis.allow_block):
def choose_scalar_style(self): if self.analysis is None: self.analysis = self.analyze_scalar(self.event.value) if self.event.style == '"' or self.canonical: return '"' if not self.event.style and self.event.implicit[0]: if (not (self.simple_key_context and (self.analysis.empty or self.analysis.multiline)) and (self.flow_level and self.analysis.allow_flow_plain or (not self.flow_level and self.analysis.allow_block_plain))): return '' if self.event.style and self.event.style in '|>': if not self.flow_level and self.analysis.allow_block: return self.event.style if not self.event.style or self.event.style == '\'': if (self.analysis.allow_single_quoted and not (self.simple_key_context and self.analysis.multiline)): return '\'' return '"'
mark = Mark(test_name, line, column, unicode(input), index)
mark = Mark(test_name, index, line, column, unicode(input), index)
def _testMarks(self, test_name, marks_filename): inputs = file(marks_filename, 'rb').read().split('---\n')[1:] for input in inputs: index = 0 line = 0 column = 0 while input[index] != '*': if input[index] == '\n': line += 1 column = 0 else: column += 1 index += 1 mark = Mark(test_name, line, column, unicode(input), index) snippet = mark.get_snippet(indent=2, max_length=79) #print "INPUT:" #print input #print "SNIPPET:" #print snippet self.failUnless(isinstance(snippet, str)) self.failUnlessEqual(snippet.count('\n'), 1) data, pointer = snippet.split('\n') self.failUnless(len(data) < 82) self.failUnlessEqual(data[len(pointer)-1], '*')
if self.check_event(StreamStartEvent): self.get_event()
def compose_document(self):
re.compile(ur'''^(?:yes|Yes|YES|n|N|no|No|NO
re.compile(ur'''^(?:yes|Yes|YES|no|No|NO
def resolve(self, kind, value, implicit): if kind is ScalarNode and implicit[0]: if value == u'': resolvers = self.yaml_implicit_resolvers.get(u'', []) else: resolvers = self.yaml_implicit_resolvers.get(value[0], []) resolvers += self.yaml_implicit_resolvers.get(None, []) for tag, regexp in resolvers: if regexp.match(value): return tag implicit = implicit[1] if self.yaml_path_resolvers: exact_paths = self.resolver_exact_paths[-1] if kind in exact_paths: return exact_paths[kind] if None in exact_paths: return exact_paths[None] if kind is ScalarNode: return self.DEFAULT_SCALAR_TAG elif kind is SequenceNode: return self.DEFAULT_SEQUENCE_TAG elif kind is MappingNode: return self.DEFAULT_MAPPING_TAG
if overwrite and not(os.path.exists(localPath)):
if overwrite or not(os.path.exists(localPath)):
def download_url(url, overwrite=False): """Download a url to the local cache @overwrite: if True overwrite an existing local copy otherwise don't """ localPath = get_local_path(url) if overwrite and not(os.path.exists(localPath)): urllib.urlretrieve(url, localPath)
s = math.sqrt(abs(m[0][0] + m[1][1] + m[2][2] + m[3][3])) if s == 0.0: x = abs(m[2][1] - m[1][2]) y = abs(m[0][2] - m[2][0]) z = abs(m[1][0] - m[0][1]) if (x >= y) and (x >= z): return 1.0, 0.0, 0.0, 0.0 elif (y >= x) and (y >= z): return 0.0, 1.0, 0.0, 0.0 else: return 0.0, 0.0, 1.0, 0.0 return quaternion_normalize([ -(m[2][1] - m[1][2]) / (2.0 * s), -(m[0][2] - m[2][0]) / (2.0 * s), -(m[1][0] - m[0][1]) / (2.0 * s), 0.5 * s, ])
tr = 1.0 + m[0][0] + m[1][1] + m[2][2] if tr > .00001: s = math.sqrt(tr) w = s / 2.0 s = 0.5 / s x = (m[1][2] - m[2][1]) * s y = (m[2][0] - m[0][2]) * s z = (m[0][1] - m[1][0]) * s elif m[0][0] > m[1][1] and m[0][0] > m[2][2]: s = math.sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]) x = s / 2.0 s = 0.5 / s y = (m[0][1] + m[1][0]) * s z = (m[2][0] + m[0][2]) * s w = (m[1][2] - m[2][1]) * s elif m[1][1] > m[2][2]: s = math.sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]) y = s / 2.0 s = 0.5 / s x = (m[0][1] + m[1][0]) * s z = (m[1][2] + m[2][1]) * s w = (m[2][0] - m[0][2]) * s else: s = math.sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]) z = s / 2.0 s = 0.5 / s x = (m[2][0] + m[0][2]) * s y = (m[1][2] + m[2][1]) * s w = (m[0][1] - m[1][0]) * s return w, x, y, z
def matrix2quaternion(m): s = math.sqrt(abs(m[0][0] + m[1][1] + m[2][2] + m[3][3])) if s == 0.0: x = abs(m[2][1] - m[1][2]) y = abs(m[0][2] - m[2][0]) z = abs(m[1][0] - m[0][1]) if (x >= y) and (x >= z): return 1.0, 0.0, 0.0, 0.0 elif (y >= x) and (y >= z): return 0.0, 1.0, 0.0, 0.0 else: return 0.0, 0.0, 1.0, 0.0 return quaternion_normalize([ -(m[2][1] - m[1][2]) / (2.0 * s), -(m[0][2] - m[2][0]) / (2.0 * s), -(m[1][0] - m[0][1]) / (2.0 * s), 0.5 * s, ])
self.file.write(struct.pack("=fff", t[1], -t[2], t[0]))
self.file.write(struct.pack("=fff", t[1], -t[2], -t[0]))
def save_frame(): for obj in self.meshes: data = Blender.NMesh.GetRawFromObject(obj.getName()) m = obj.getMatrix() # action/frame/mesh/vertices for nv in self.objvertmaps[obj.getName()]: v = data.verts[nv] t = [0, 0, 0] t[0] = m[0][0]*v[0] + m[1][0]*v[1] + m[2][0]*v[2] + m[3][0] t[1] = m[0][1]*v[0] + m[1][1]*v[1] + m[2][1]*v[2] + m[3][1] t[2] = m[0][2]*v[0] + m[1][2]*v[1] + m[2][2]*v[2] + m[3][2] t[0] *= ZOOM t[1] *= ZOOM t[2] *= ZOOM self.file.write(struct.pack("=fff", t[1], -t[2], t[0]))
self.file.write(struct.pack("=fff", loc[0], loc[1], loc[2]))
self.file.write(struct.pack("=fff", loc[1], -loc[2], -loc[0]))
def save_frame(): for obj in self.meshes: data = Blender.NMesh.GetRawFromObject(obj.getName()) m = obj.getMatrix() # action/frame/mesh/vertices for nv in self.objvertmaps[obj.getName()]: v = data.verts[nv] t = [0, 0, 0] t[0] = m[0][0]*v[0] + m[1][0]*v[1] + m[2][0]*v[2] + m[3][0] t[1] = m[0][1]*v[0] + m[1][1]*v[1] + m[2][1]*v[2] + m[3][1] t[2] = m[0][2]*v[0] + m[1][2]*v[1] + m[2][2]*v[2] + m[3][2] t[0] *= ZOOM t[1] *= ZOOM t[2] *= ZOOM self.file.write(struct.pack("=fff", t[1], -t[2], t[0]))
bodydata += struct.pack("=fff", face.normal[1], -face.normal[2], face.normal[0])
bodydata += struct.pack("=fff", face.normal[1], -face.normal[2], -face.normal[0])
def mapvertex(index, u, v): for mv in xrange(0, len(vertexmap)): if vertexmap[mv] == index and uvs[mv] == (u, v): return mv vertexmap.append(index) uvs.append( (u, v) ) return len(vertexmap)-1
bodydata += struct.pack("=fff", face.normal[0], face.normal[1], face.normal[2])
bodydata += struct.pack("=fff", face.normal[1], -face.normal[2], face.normal[0])
def mapvertex(index, u, v): for mv in xrange(0, len(vertexmap)): if vertexmap[mv] == index and uvs[mv] == (u, v): return mv vertexmap.append(index) uvs.append( (u, v) ) return len(vertexmap)-1
for frame in xrange(1, numframes+1, SAMPLEFRAMES):
for frame in range(1, numframes+1, SAMPLEFRAMES):
def mapvertex(index, u, v): for mv in xrange(0, len(vertexmap)): if vertexmap[mv] == index and uvs[mv] == (u, v): return mv vertexmap.append(index) uvs.append( (u, v) ) return len(vertexmap)-1
Blender.Set("curframe", frame.__int__())
Blender.Set("curframe", float(frame))
def mapvertex(index, u, v): for mv in xrange(0, len(vertexmap)): if vertexmap[mv] == index and uvs[mv] == (u, v): return mv vertexmap.append(index) uvs.append( (u, v) ) return len(vertexmap)-1
file.write(struct.pack("=fff", t[0], t[1], t[2])) print frs
file.write(struct.pack("=fff", t[1], -t[2], t[0]))
def mapvertex(index, u, v): for mv in xrange(0, len(vertexmap)): if vertexmap[mv] == index and uvs[mv] == (u, v): return mv vertexmap.append(index) uvs.append( (u, v) ) return len(vertexmap)-1
file.write(struct.pack("=64sH", marker[0], marker[1]))
file.write(struct.pack("=64sH", marker[0], \ blenderframe_to_wspriteframe(marker[1])))
def mapvertex(index, u, v): for mv in xrange(0, len(vertexmap)): if vertexmap[mv] == index and uvs[mv] == (u, v): return mv vertexmap.append(index) uvs.append( (u, v) ) return len(vertexmap)-1
if file[-4:] == ".tex": file = file[:-4] aux = basename(file) + ".aux"
aux = dict["arg"] + ".aux"
def h_include (self, dict): """ Called when an \\include macro is found. This includes files into the source in a way very similar to \\input, except that LaTeX also creates .aux files for them, so we have to notice this. """ if not dict["arg"]: return if self.include_only and not self.include_only.has_key(dict["arg"]): return file, _ = self.input_file(dict["arg"], dict) if file: if file[-4:] == ".tex": file = file[:-4] aux = basename(file) + ".aux" self.removed_files.append(aux) self.aux_old[aux] = None if exists(aux): self.aux_md5[aux] = md5_file(aux) else: self.aux_md5[aux] = None
if self.opts.has_key("ext"):
opts = rubber.util.parse_keyval(dict["opt"]) if opts.has_key("ext"):
def includegraphics (self, dict): """ This method is triggered by th \\includegraphics macro, it looks for the graphics file specified as argument and adds it either to the dependencies or to the list of graphics not found. """ name = dict["arg"] suffixes = self.suffixes
if self.opts["ext"]: name = name + self.opts["ext"]
if opts["ext"]: name = name + opts["ext"]
def includegraphics (self, dict): """ This method is triggered by th \\includegraphics macro, it looks for the graphics file specified as argument and adds it either to the dependencies or to the list of graphics not found. """ name = dict["arg"] suffixes = self.suffixes
deps = []
deps = {}
def main (self, cmdline): self.env = Environment(self.msg) self.modules = []
deps.extend(dep.leaves()) print string.join(deps)
for file in dep.leaves(): deps[file] = None print string.join(deps.keys())
def main (self, cmdline): self.env = Environment(self.msg) self.modules = []
({(?P<arg>[^\\\\{}]*)}|[^A-Za-z{])?"
({(?P<arg>[^\\\\{}]*)}|(?=[^A-Za-z]))"
def update_seq (self): """ Update the regular expression used to match macro calls using the keys in the `hook' dictionary. We don't match all control sequences for obvious efficiency reasons. """ self.seq = re.compile("\
else: self.update_file(line, pos)
def show_errors (self): """ Display all errors that occured during compilation. Return 0 if there was no error. """ pos = ["(no file)"] last_file = None showing = 0 # 1 if we are showing an error's text skipping = 0 # 1 if we are skipping text until a new line something = 0 # 1 if some error was displayed for line in self.lines: line = line.rstrip() if line == "": skipping = 0 elif skipping: pass elif showing: self.msg(0, line) if line[0:2] == "l." or line[0:3] == "***": showing = 0 skipping = 1 else: self.update_file(line, pos) elif line[0] == "!": if pos[-1] != last_file: last_file = pos[-1] self.msg(0, _("in file %s:") % last_file) self.msg(0, line) showing = 1 something = 1 else:
self.pbase = doc.src_base
def __init__ (self, doc, source, target, transcript): """ Initialize the index, by specifying the source file (generated by LaTeX), the target file (the output of makeindex) and the transcript (e.g. .ilg) file. Transcript is used by glosstex.py. """ self.doc = doc self.pbase = doc.src_base self.source = doc.src_base + "." + source self.target = doc.src_base + "." + target self.transcript = doc.src_base + "." + transcript if os.path.exists(self.source): self.md5 = md5_file(self.source) else: self.md5 = None
cmd = ["makeindex", "-o", self.target] + self.opts
cmd = ["makeindex", "-q", "-o", self.target] + self.opts
def post_compile (self): """ Run makeindex if needed, with appropriate options and environment. """ if not os.path.exists(self.source): msg.log(_("strange, there is no %s") % self.source, pkg="index") return 0 if not self.run_needed(): return 0
cmd.append(self.pbase)
cmd.append(self.source)
def post_compile (self): """ Run makeindex if needed, with appropriate options and environment. """ if not os.path.exists(self.source): msg.log(_("strange, there is no %s") % self.source, pkg="index") return 0 if not self.run_needed(): return 0
env.msg(2, "%s is made from %r" % (target, sources))
env.msg(2, _("%s is made from %r") % (target, sources))
def __init__ (self, target, source, env): sources = [] self.include(source, sources) env.msg(2, "%s is made from %r" % (target, sources)) self.leaf = DependLeaf(sources) Depend.__init__(self, [target], {source: self.leaf}) self.env = env self.base = source[:-3] self.cmd = ["mpost", "--interaction=batchmode", self.base] if env.src_path != "": cmd = [ "env", "MPINPUTS=:%s:%s" % (self.env.src_path, os.getenv("MPINPUTS", ""))] + cmd
self.env.msg(0, "running Metapost on %s.mp..." % self.base)
self.env.msg(0, _("running Metapost on %s.mp...") % self.base)
def run (self): self.env.msg(0, "running Metapost on %s.mp..." % self.base) self.env.execute(self.cmd)
self.msg(0, line.rstrip())
self.env.msg(0, line.rstrip())
def run (self): self.env.msg(0, "running Metapost on %s.mp..." % self.base) self.env.execute(self.cmd)
self.msg(0, _("There were errors in Metapost code:")) self.msg(0, line.rstrip())
self.env.msg(0, _("There were errors in Metapost code:")) self.env.msg(0, line.rstrip())
def run (self): self.env.msg(0, "running Metapost on %s.mp..." % self.base) self.env.execute(self.cmd)
if errors: d = { "kind": "error", "text": error,
pdfTeX = string.find(line, "pdfTeX warning") == -1 if (pdfTeX and warnings) or (errors and not pdfTeX): if pdfTeX: d = { "kind": "warning", "pkg": "pdfTeX", "text": error[error.find(":")+2:] } else: d = { "kind": "error", "text": error
def parse (self, errors=0, boxes=0, refs=0, warnings=0): """ Parse the log file for relevant information. The named arguments are booleans that indicate which information should be extracted: - errors: all errors - boxes: bad boxes - refs: warnings about references - warnings: all other warnings The function returns a generator. Each generated item is a dictionary that contains (some of) the following entries: - kind: the kind of information ("error", "box", "ref", "warning") - text: the text of the error or warning - code: the piece of code that caused an error - file, line, last, pkg: as used by Message.format_pos. """ if not self.lines: return last_file = None pos = [last_file] page = 1 parsing = 0 # 1 if we are parsing an error's text skipping = 0 # 1 if we are skipping text until an empty line something = 0 # 1 if some error was found prefix = None # the prefix for warning messages from packages accu = "" # accumulated text from the previous line for line in self.lines: line = line[:-1] # remove the line feed
self.path = [""] if doc.src_path != "" and doc.src_path != ".": self.path.append(doc.src_path) self.style = None
self.tool = "makeindex" self.lang = None self.modules = []
def __init__ (self, doc, source, target, transcript): """ Initialize the index, by specifying the source file (generated by LaTeX), the target file (the output of makeindex) and the transcript (e.g. .ilg) file. Transcript is used by glosstex.py. """ self.doc = doc self.pbase = doc.src_base self.source = doc.src_base + "." + source self.target = doc.src_base + "." + target self.transcript = doc.src_base + "." + transcript if os.path.exists(self.source): self.md5 = md5_file(self.source) else: self.md5 = None
cmd = ["makeindex", "-o", self.target] + self.opts cmd.extend(["-t", self.transcript]) if self.style: cmd.extend(["-s", self.style]) cmd.append(self.pbase) if self.path != [""]: env = { 'INDEXSTYLE': string.join(self.path + [os.getenv("INDEXSTYLE", "")], ":") }
if self.tool == "makeindex": cmd = ["makeindex", "-o", self.target] + self.opts cmd.extend(["-t", self.transcript]) if self.style: cmd.extend(["-s", self.style]) cmd.append(self.pbase) path_var = "INDEXSTYLE" elif self.tool == "xindy": cmd = ["texindy", "--quiet"] for opt in self.opts: if opt == "-g": if self.lang != "": msg.warn(_("'language' overrides 'order german'"), pkg="index") else: self.lang = "german-din" elif opt == "-l": self.modules.append("letter-ordering") msg.warn(_("use 'module letter-ordering' instead of 'order letter'"), pkg="index") else: msg.error("unknown option to xindy: %s" % opt, pkg="index") for mod in self.modules: cmd.extend(["--module", mod]) if self.lang: cmd.extend(["--language", self.lang]) cmd.append(self.source) path_var = "XINDY_SEARCHPATH" if self.path != []: env = { path_var: string.join(self.path + [os.getenv(path_var, "")], ":") }
def post_compile (self): """ Run makeindex if needed, with appropriate options and environment. """ if not os.path.exists(self.source): msg.log(_("strange, there is no %s") % self.source, pkg="index") return 0 if not self.run_needed(): return 0
msg.error(_("makeindex failed on %s") % self.source)
msg.error(_("could not make index %s") % self.target)
def post_compile (self): """ Run makeindex if needed, with appropriate options and environment. """ if not os.path.exists(self.source): msg.log(_("strange, there is no %s") % self.source, pkg="index") return 0 if not self.run_needed(): return 0
self.indices["default"] = Index(self.doc, "idx", "ind", "ilg")
self.register("default", "idx", "ind", "ilg")
def makeindex (self, dict): """ Register the standard index. """ self.indices["default"] = Index(self.doc, "idx", "ind", "ilg")
self.indices[index] = Index(self.doc, d["idx"], d["ind"], "ilg")
self.register(index, d["idx"], d["ind"], "ilg")
def newindex (self, dict): """ Register a new index. """ m = re_newindex.match(dict["line"]) if not m: return index = dict["arg"] d = m.groupdict() self.indices[index] = Index(self.doc, d["idx"], d["ind"], "ilg") msg.log(_("index %s registered") % index, pkg="index")
for index in m.group("list").split(","): if indices.has_key(index): indices[index].command(cmd, args[1:]) else: for index in indices.values(): index.command(cmd, args)
names = m.group("list").split(",") args = args[1:] if names is None: self.defaults.append([cmd, args]) names = indices.keys() for index in names: if indices.has_key(index): indices[index].command(cmd, args[1:]) elif self.commands.has_key(index): self.commands[index].append([cmd, args]) else: self.commands[index] = [[cmd, args]]
def command (self, cmd, args): indices = self.indices if len(args) > 0: m = re_optarg.match(args[0]) if m: for index in m.group("list").split(","): if indices.has_key(index): indices[index].command(cmd, args[1:]) else: for index in indices.values(): index.command(cmd, args)
if exists(test):
if exists(test) and isfile(test):
def find_input (self, name): """ Look for a source file with the given name, and return either the complete path to the actual file or None if the file is not found. """ for path in self.path: test = join(path, name) if exists(test): return test elif exists(test + ".tex"): return test + ".tex" return None
elif exists(test + ".tex"):
elif exists(test + ".tex") and isfile(test + ".tex"):
def find_input (self, name): """ Look for a source file with the given name, and return either the complete path to the actual file or None if the file is not found. """ for path in self.path: test = join(path, name) if exists(test): return test elif exists(test + ".tex"): return test + ".tex" return None
pdfTeX = string.find(line, "pdfTeX warning") == -1
pdfTeX = string.find(line, "pdfTeX warning") != -1
def parse (self, errors=0, boxes=0, refs=0, warnings=0): """ Parse the log file for relevant information. The named arguments are booleans that indicate which information should be extracted: - errors: all errors - boxes: bad boxes - refs: warnings about references - warnings: all other warnings The function returns a generator. Each generated item is a dictionary that contains (some of) the following entries: - kind: the kind of information ("error", "box", "ref", "warning") - text: the text of the error or warning - code: the piece of code that caused an error - file, line, last, pkg: as used by Message.format_pos. """ if not self.lines: return last_file = None pos = [last_file] page = 1 parsing = 0 # 1 if we are parsing an error's text skipping = 0 # 1 if we are skipping text until an empty line something = 0 # 1 if some error was found prefix = None # the prefix for warning messages from packages accu = "" # accumulated text from the previous line for line in self.lines: line = line[:-1] # remove the line feed
if self.env.may_produce(source):
if exists(target) and self.env.may_produce(source):
def check (source, target, suffixes=suffixes): if self.env.may_produce(source): return 0 if suffixes == [""]: return 1 for suffix in suffixes: if source[-len(suffix):] == suffix: return 0 return 1
do_check()
ret = do_check() sys.exit(ret)
def do_setup (): """ Run the setup() function from the distutils with appropriate arguments. """ from distutils.core import setup try: mandir = expand_vars(settings.sub, settings.sub["mandir"]) except NameError: mandir = "man" setup( name = "rubber", version = settings.sub["version"], description = "The Rubber system for building LaTeX documents", long_description = """\
re_file = re.compile("(\\((?P<file>[^ ()]*)|\\))")
re_file = re.compile("(\\((?P<file>[^ (){}]*)|\\))")
def register (self, name, dict={}): """ Attempt to register a package with the specified name. If a module is found, create an object from the module's class called `Module', passing it the environment and `dict' as arguments. This dictionary describes the command that caused the registration. """ r = self.load_module(name, "rubber.modules") if r == 0: self.env.msg(3, _("no support found for %s") % name) return 1 elif r == 2: self.env.msg(3, _("module %s already registered") % name) return 1 mod = self.modules[name].Module(self.env, dict) self.env.msg(2, _("module %s registered") % name) self.objects[name] = mod return 0
file = m.group("file") if file: stack.append(file)
if line[m.start()] == '(': stack.append(m.group("file"))
def update_file (self, line, stack): """ Parse the given line of log file for file openings and closings and update the list `stack'. Newly opened files are at the end, therefore stack[0] is the main source while stack[-1] is the current one. """ m = re_file.search(line) if not m: return while m: file = m.group("file") if file: stack.append(file) else: del stack[-1] line = line[m.end():] m = re_file.search(line) return
for file in self.source, self.target:
for file in self.source, self.target, self.pbase + ".ilg":
def clean (self): """ Remove all generated files related to the index. """ for file in self.source, self.target: if exists(file): self.env.msg(1, _("removing %s") % file) os.unlink(file)
return 1
return string.find(line, "warning:") != -1
def errors (self): """ Returns true if there was an error during the compilation. """ for line in self.lines: if line[0] == "!": return 1 return 0
if cmd == "depend":
if cmd == "clean": self.removed_files.append(arg) elif cmd == "depend":
def command (self, cmd, arg): """ Execute the rubber command 'cmd' with argument 'arg'. This is called when a command is found in the source file or in a configuration file. A command name of the form 'foo.bar' is considered to be a command 'bar' for module 'foo'. """ if cmd == "depend": file = self.conf.find_input(arg) if file: self.depends[file] = DependLeaf([file]) else: self.msg(1, _("dependency '%s' not found") % arg)
self.watch_file(self.base + ".toc")
self.watch_file(self.src_base + ".toc")
def h_tableofcontents (self, dict): self.watch_file(self.base + ".toc")
self.watch_file(self.base + ".lof")
self.watch_file(self.src_base + ".lof")
def h_listoffigures (self, dict): self.watch_file(self.base + ".lof")
self.watch_file(self.base + ".lot")
self.watch_file(self.src_base + ".lot")
def h_listoftables (self, dict): self.watch_file(self.base + ".lot")
self.date = time.time()
self.date = int(time.time())
def make (self): """ Make the destination file. This recursively makes all dependencies, then compiles the target if dependencies were modified. The semantics of the return value is the following: - 0 means that the process failed somewhere (in this node or in one of its dependencies) - 1 means that nothing had to be done - 2 means that something was recompiled (therefore nodes that depend on this one have to be remade) """ must_make = 0 for src in self.sources.values(): ret = src.make() if ret == 0: return 0 if ret == 2: must_make = 1 if must_make or self.should_make(): if self.run(): return 0 self.date = time.time() return 2 return 1
if string.strip(code) != "":
if code:
def error (self, file, line, text, code): """ This method is called when the parsing of the log file found an error. The arguments are, respectively, the name of the file and the line number where the error occurred, the description of the error, and the offending code (up to the error). """ self.write(0, _("\nline %d in %s:\n %s") % (line, file, text)) if string.strip(code) != "": self.write(0, " --> " + code)
re_line = re.compile("l\\.(?P<line>[0-9]+) ")
re_line = re.compile("l\\.(?P<line>[0-9]+)( (?P<text>.*))?$")
def register (self, name, dict={}): """ Attempt to register a package with the specified name. If a module is found, create an object from the module's class called `Module', passing it the environment and `dict' as arguments. This dictionary describes the command that caused the registration. """ r = self.load_module(name, "rubber.modules") if r == 0: self.env.msg(3, _("no support found for %s") % name) return 1 elif r == 2: self.env.msg(3, _("module %s already registered") % name) return 1 mod = self.modules[name].Module(self.env, dict) self.env.msg(2, _("module %s registered") % name) self.objects[name] = mod return 0
error, line[m.end():])
error, m.group("text"))
def show_errors (self): """ Display all errors that occured during compilation. Return 0 if there was no error. """ pos = ["(no file)"] last_file = None parsing = 0 # 1 if we are parsing an error's text skipping = 0 # 1 if we are skipping text until an empty line something = 0 # 1 if some error was found for line in self.lines: line = line.rstrip() if line == "": skipping = 0 elif skipping: pass elif parsing: m = re_line.match(line) if m: parsing = 0 skipping = 1 self.msg.error(pos[-1], int(m.group("line")), error, line[m.end():]) elif line[0:3] == "***": parsing = 0 skipping = 1 self.msg.abort(error, line[4:]) elif line[0] == "!": error = line[2:] parsing = 1 something = 1 else: # Here there is no error to show, so we use the text of the # line to track the source file name. However, there might be # confusing text in the log file, in particular when there is # an overfull/underfull box message (the text following this # is extracted from the source, and the extract may contain # unbalanced parentheses). Therefore we take care of this # specifically.
old_bst = self.style + ".bst" if exists(old_bst) and self.env.depends.has_key(old_bst): del self.env.depends[old_bst]
if self.style: old_bst = self.style + ".bst" if exists(old_bst) and self.env.depends.has_key(old_bst): del self.env.depends[old_bst]
def set_style (self, style): """ Define the bibliography style used. This method is called when \\bibliographystyle is found. If the style file is found in the current directory, it is considered a dependency. """ old_bst = self.style + ".bst" if exists(old_bst) and self.env.depends.has_key(old_bst): del self.env.depends[old_bst]
re_file = re.compile("(\((?P<file>[^ ()]*)|\))")
re_file = re.compile("(\\((?P<file>[^ ()]*)|\\))") re_badbox = re.compile("(Ov|Und)erfull \\\\[hv]box ")
def register (self, name, dict={}): """ Attempt to register a package with the specified name. If a module is found, create an object from the module's class called `Module', passing it the environment and `dict' as arguments. This dictionary describes the command that caused the registration. """ r = self.load_module(name, "rubber.modules") if r == 0: self.env.msg(3, _("no support found for %s") % name) return 1 elif r == 2: self.env.msg(3, _("module %s already registered") % name) return 1 mod = self.modules[name].Module(self.env, dict) self.env.msg(2, _("module %s registered") % name) self.objects[name] = mod return 0
stack[0] is the main source while stack[-1] is the current one.
stack[1] is the main source while stack[-1] is the current one. The first element, stack[0], contains the string \"(no file)\" for errors that may happen outside the source.
def update_file (self, line, stack): """ Parse the given line of log file for file openings and closings and update the list `stack'. Newly opened files are at the end, therefore stack[0] is the main source while stack[-1] is the current one. """ m = re_file.search(line) if not m: return while m: if line[m.start()] == '(': stack.append(m.group("file")) else: del stack[-1] line = line[m.end():] m = re_file.search(line) return
showing = 0 something = 0
showing = 0 skipping = 0 something = 0
def show_errors (self): """ Display all errors that occured during compilation. Return 0 if there was no error. """ pos = ["(no file)"] last_file = None showing = 0 something = 0 for line in self.lines: line = line.rstrip() if line == "": continue if showing: self.msg(0, line) if line[0:2] == "l." or line[0:3] == "***": showing = 0 else: self.update_file(line, pos) else: if line[0] == "!": if pos[-1] != last_file: last_file = pos[-1] self.msg(0, _("in file %s:") % last_file) self.msg(0, line) showing = 1 something = 1 else: self.update_file(line, pos) return something
continue if showing:
skipping = 0 elif skipping: pass elif showing:
def show_errors (self): """ Display all errors that occured during compilation. Return 0 if there was no error. """ pos = ["(no file)"] last_file = None showing = 0 something = 0 for line in self.lines: line = line.rstrip() if line == "": continue if showing: self.msg(0, line) if line[0:2] == "l." or line[0:3] == "***": showing = 0 else: self.update_file(line, pos) else: if line[0] == "!": if pos[-1] != last_file: last_file = pos[-1] self.msg(0, _("in file %s:") % last_file) self.msg(0, line) showing = 1 something = 1 else: self.update_file(line, pos) return something
if line[0] == "!": if pos[-1] != last_file: last_file = pos[-1] self.msg(0, _("in file %s:") % last_file) self.msg(0, line) showing = 1 something = 1
m = re_badbox.match(line) if m: skipping = 1
def show_errors (self): """ Display all errors that occured during compilation. Return 0 if there was no error. """ pos = ["(no file)"] last_file = None showing = 0 something = 0 for line in self.lines: line = line.rstrip() if line == "": continue if showing: self.msg(0, line) if line[0:2] == "l." or line[0:3] == "***": showing = 0 else: self.update_file(line, pos) else: if line[0] == "!": if pos[-1] != last_file: last_file = pos[-1] self.msg(0, _("in file %s:") % last_file) self.msg(0, line) showing = 1 something = 1 else: self.update_file(line, pos) return something
msg.warn(_("dependency '%s' not found") % arg, **pos)
msg.warn(_("dependency '%s' not found") % arg, **self.vars)
def do_depend (self, *args): for arg in args: file = self.env.find_file(arg) if file: self.sources[file] = DependLeaf(self.env, file) else: msg.warn(_("dependency '%s' not found") % arg, **pos)
return 0 if self.undef_cites != new:
elif self.undef_cites != new:
def bibtex_needed (self): """ Return true if BibTeX must be run. """ if self.run_needed: return 1 self.msg(2, _("checking if BibTeX must be run..."))
self.msg(2, _("the undefined citations are the same")) return 0 self.undef_cites = self.list_undefs()
else: self.msg(2, _("the undefined citations are the same")) else: self.undef_cites = self.list_undefs()
def bibtex_needed (self): """ Return true if BibTeX must be run. """ if self.run_needed: return 1 self.msg(2, _("checking if BibTeX must be run..."))
penv = posix.environ
penv = posix.environ.copy()
def execute (self, prog, env={}): """ Silently execute an external program. The `prog' argument is the list of arguments for the program, `prog[0]' is the program name. The `env' argument is a dictionary with definitions that should be added to the environment when running the program. The output is dicarded, but messages from Kpathsea are processed (to indicate e.g. font compilation). """ self.msg(1, _("executing: %s") % string.join(prog)) if env != {}: self.msg(2, _("with environment: %r") % env)
for line in file.readlines():
for line in fd.readlines():
def include (self, source, list): """ This function tries to find a specified MetaPost source (currently all in the same directory), appends its actual name to the list, and parses it to find recursively included files. """ if exists(source + ".mp"): file = source + ".mp" elif exists(source): file = source else: return list.append(file) fd = open(file) for line in file.readlines(): m = re_input.search(line) if m: self.include(m["file"]) fd.close()
self.include(m["file"])
self.include(m.group("file"), list)
def include (self, source, list): """ This function tries to find a specified MetaPost source (currently all in the same directory), appends its actual name to the list, and parses it to find recursively included files. """ if exists(source + ".mp"): file = source + ".mp" elif exists(source): file = source else: return list.append(file) fd = open(file) for line in file.readlines(): m = re_input.search(line) if m: self.include(m["file"]) fd.close()
self.base = target[:-3]
self.base = source[:-3]
def __init__ (self, target, source, env): leaf = DependLeaf([source]) Depend.__init__(self, [target], {source: leaf}) self.env = env self.base = target[:-3] self.cmd = ["mpost", "--interaction=batchmode", self.base]
pos = []
pos = ["(no file)"]
def show_boxes (self): """ Display all messages related so underfull and overfull boxes. Return 0 if there is nothing to display. """ pos = [] page = 1 something = 0 for line in self.lines: line = line.rstrip() if re_hvbox.match(line): self.msg.info({"file":pos[-1], "page":page}, line) something = 1 else: self.update_file(line, pos) page = self.update_page(line, page) return something
if re_hvbox.match(line):
if skip: if line == "": skip = 0 elif re_hvbox.match(line):
def show_boxes (self): """ Display all messages related so underfull and overfull boxes. Return 0 if there is nothing to display. """ pos = [] page = 1 something = 0 for line in self.lines: line = line.rstrip() if re_hvbox.match(line): self.msg.info({"file":pos[-1], "page":page}, line) something = 1 else: self.update_file(line, pos) page = self.update_page(line, page) return something
pos = []
pos = ["(no file)"]
def show_warnings (self): """ Display all warnings. This function is pathetically dumb, as it simply shows all lines in the log that contain the substring 'Warning'. """ pos = [] page = 1 something = 0 for line in self.lines: if line.find("Warning") != -1: self.msg.info( {"file":pos[-1], "page":page}, string.rstrip(line)) something = 1 else: self.update_file(line, pos) page = self.update_page(line, page) return something
if line.find("Warning") != -1:
if skip: if line == "": skip = 0 elif re_hvbox.match(line): skip = 1 elif line.find("Warning") != -1:
def show_warnings (self): """ Display all warnings. This function is pathetically dumb, as it simply shows all lines in the log that contain the substring 'Warning'. """ pos = [] page = 1 something = 0 for line in self.lines: if line.find("Warning") != -1: self.msg.info( {"file":pos[-1], "page":page}, string.rstrip(line)) something = 1 else: self.update_file(line, pos) page = self.update_page(line, page) return something
self.cmd_t = ["fig2dev", "-L", lang + "_t", "-p", epsname, fig, tex ]
self.cmd_t = ["fig2dev", "-L", lang + "_t", "-p", os.path.basename(epsname), fig, tex ]
def __init__ (self, env, tex, fig, vars, module=None, loc={}): """ The arguments of the constructor are, respectively, the figure's source, the LaTeX source produced, the EPS figure produced, the name to use for it (probably the same one), and the environment. """ leaf = DependLeaf(env, fig, loc=loc) self.env = env
file, path, descr = imp.find_module(join(pname, name));
file, path, descr = imp.find_module(os.path.join(pname, name));
def load_module (self, name, package=None): """ Attempt to register a module with the specified name. If an appropriate module is found, load it and store it in the object's dictionary. Return 0 if no module was found, 1 if a module was found and loaded, and 2 if the module was found but already loaded. """ if self.modules.has_key(name): return 2 try: file, path, descr = imp.find_module(name, [""]) except ImportError: if not package: return 0 try: pname = "" for p in package.split("."): pname = os.path.join(pname, p) file, path, descr = imp.find_module(join(pname, name)); except ImportError: return 0 module = imp.load_module(name, file, path, descr) file.close() self.modules[name] = module return 1
return None, None
def do_watch (self, *args): for arg in args: self.watch_file(arg)
self.failed_dep = mod
self.failed_module = mod
def pre_compile (self): """ Prepare the source for compilation using package-specific functions. This function must return true on failure. This function sets `must_compile' to 1 if we already know that a compilation is needed, because it may avoid some unnecessary preprocessing (e.g. BibTeXing). """ if os.path.exists(self.src_base + ".aux"): self.aux_md5 = md5_file(self.src_base + ".aux") else: self.aux_md5 = None self.aux_md5_old = None
self.failed_dep = mod
self.failed_module = mod
def post_compile (self): """ Run the package-specific operations that are to be performed after each compilation of the main source. Returns true on failure. """ msg.log(_("running post-compilation scripts..."))
self.log.show_errors()
if self.failed_module is None: self.log.show_errors() else: self.failed_module.show_errors()
def show_errors (self): self.log.show_errors()
env.add_hook("listinginput", self.input)
env.add_hook("listinginput", self.listinginput)
def __init__ (self, env, dict): self.env = env env.add_hook("verbatimtabinput", self.input) env.add_hook("listinginput", self.input)
bbl = env.src_base + ".bbl"
def __init__ (self, env, dict): """ Initialize the state of the module and register appropriate functions in the main process. """ self.env = env self.msg = env.msg
Run BibTeX if needed before the first compilation.
Run BibTeX if needed before the first compilation. This function also checks if BibTeX has been run by someone else, and in this case it tells the system that it should recompile the document.
def first_bib (self): """ Run BibTeX if needed before the first compilation. """ self.run_needed = self.first_run_needed() if self.env.must_compile: return 0 if self.run_needed: return self.run()
if self.env.execute(["bibtex", "-terse", self.env.src_base], env):
if self.env.execute(["bibtex", self.env.src_base], env):
def run (self): """ This method actually runs BibTeX. """ self.msg(0, _("running BibTeX...")) if self.env.src_path != "": env = { "BIBINPUTS": "%s:%s" % (self.env.src_path, os.getenv("BIBINPUTS", "")) } else: env = {} if self.env.execute(["bibtex", "-terse", self.env.src_base], env): self.env.msg(0, _( "There were errors running BibTeX (see %s for details)." ) % (self.env.src_base + ".blg")) return 1 self.run_needed = 0 self.env.must_compile = 1 return 0
if string.find(line, "warning:") == -1:
if string.find(line, "pdfTeX warning") == -1:
def errors (self): """ Returns true if there was an error during the compilation. """ for line in self.lines: if line[0] == "!": # We check for the substring "warning:" because pdfTeX # sometimes issues warnings (like undefined references) in the # form of errors...
self.env.process.src_pbase, self.env.process.out_ext, string.join(self.env.process.depends.keys()))
self.env.src_base, self.env.out_ext, string.join(self.env.depends.keys()))
def main (self, cmdline): self.env = Environment(self.msg) self.modules = [] self.act = None args = self.parse_opts(cmdline) self.msg(1, _( "This is Rubber's information extractor version %s.") % version)
if self.env.prepare(src):
if self.env.set_source(src): sys.exit(1) if self.env.make_source():
def prepare (self, src): """ Check for the source file and prepare it for processing. """ if self.env.prepare(src): sys.exit(1) for mod in self.modules: colon = mod.find(":") if colon == -1: if self.env.modules.register(mod, { "arg": mod, "opt": None }): self.msg( 0, _("module %s could not be registered") % mod) else: arg = { "arg": mod[:colon], "opt": mod[colon+1:] } mod = mod[0:colon] if self.env.modules.register(mod, arg): self.msg( 0, _("module %s could not be registered") % mod) self.env.parse()
"tcidvi" : [""], "textures" : ["", ".ps", ".eps", ".pict"],
"tcidvi" : [], "textures" : [".ps", ".eps", ".pict"],
# default suffixes for each device driver (taken from the .def files)
saved = self.vars.copy()
saved = {}
def push_vars (self, **dict): """ For each named argument "key=val", save the value of variable "key" and assign it the value "val". """ saved = self.vars.copy() for (key, val) in dict.items(): self.vars[key] = val self.vars_stack.append(saved)