def addconstant(self, constant): "Add a constant value." if constant in Grammar.instance.constants: Trace.error('Repeated constant ' + constant) return Trace.debug('New constant: ' + constant) self.pieces.append(ConstantWord(constant))
def parsecomma(self, tag): "Parse an author with a comma: Python, M." bits = tag.split(',') if len(bits) > 2: Trace.error('Too many commas in ' + tag) self.surname = bits[0].strip() self.parsefirstnames(bits[1].strip())
def parseending(self, reader, process): "Parse until the current ending is found" if not self.ending: Trace.error('No ending for ' + str(self)) return while not reader.currentline().startswith(self.ending): process()
def parseany(self, pos): "Parse any formula bit at the current location." for type in self.types + self.skippedtypes: if self.detecttype(type, pos): return self.parsetype(type, pos) Trace.error('Unrecognized formula at ' + pos.identifier()) return FormulaConstant(pos.skipcurrent())
def process(self): self.type = self.header[1] if not self.type in TagConfig.shaped: Trace.error('Unrecognized shape ' + self.header[1]) self.output.tag = 'span' return self.output.tag = TagConfig.shaped[self.type]
def parseformula(self, reader): "Parse the formula contents" simple = FormulaConfig.starts['simple'] if simple in reader.currentline(): rest = reader.currentline().split(simple, 1)[1] if simple in rest: # formula is $...$ return self.parsesingleliner(reader, simple, simple) # formula is multiline $...$ return self.parsemultiliner(reader, simple, simple) if FormulaConfig.starts['complex'] in reader.currentline(): # formula of the form \[...\] return self.parsemultiliner(reader, FormulaConfig.starts['complex'], FormulaConfig.endings['complex']) beginbefore = FormulaConfig.starts['beginbefore'] beginafter = FormulaConfig.starts['beginafter'] if beginbefore in reader.currentline(): if reader.currentline().strip().endswith(beginafter): current = reader.currentline().strip() endsplit = current.split(beginbefore)[1].split(beginafter) startpiece = beginbefore + endsplit[0] + beginafter endbefore = FormulaConfig.endings['endbefore'] endafter = FormulaConfig.endings['endafter'] endpiece = endbefore + endsplit[0] + endafter return startpiece + self.parsemultiliner(reader, startpiece, endpiece) + endpiece Trace.error('Missing ' + beginafter + ' in ' + reader.currentline()) return '' begincommand = FormulaConfig.starts['command'] beginbracket = FormulaConfig.starts['bracket'] if begincommand in reader.currentline() and beginbracket in reader.currentline(): endbracket = FormulaConfig.endings['bracket'] return self.parsemultiliner(reader, beginbracket, endbracket) Trace.error('Formula beginning ' + reader.currentline() + ' is unknown') return ''
def gethtml(self): "Get the resulting HTML" html = self.output.gethtml(self) if isinstance(html, basestring): Trace.error('Raw string ' + html) html = [html] return self.escapeall(html)
def isout(self): "Find out if we are out of the text yet." if self.pos > len(self.reader.currentline()): if self.pos > len(self.reader.currentline()) + 1: Trace.error('Out of the line ' + self.reader.currentline() + ': ' + unicode(self.pos)) self.nextline() return self.reader.finished()
def process(self): "Show warning if version < 276" version = int(self.header[1]) if version < 276: Trace.error('Warning: unsupported old format version ' + str(version)) if version > int(GeneralConfig.version['lyxformat']): Trace.error('Warning: unsupported new format version ' + str(version))
def add(self, pieces): "Add a new set of alternative pieces." alternative = Declaration('#' + str(len(self.alternatives))) alternative.pieces = pieces self.alternatives.append(alternative) Trace.debug('Alternatives: ' + str(self)) return self
def formatcontents(self): "Format the reference contents." formatkey = self.getparameter('LatexCommand') if not formatkey: formatkey = 'ref' self.formatted = u'↕' if formatkey in StyleConfig.referenceformats: self.formatted = StyleConfig.referenceformats[formatkey] else: Trace.error('Unknown reference format ' + formatkey) self.replace(u'↕', self.direction) self.replace('#', '1') self.replace('on-page', Translator.translate('on-page')) partkey = self.destination.findpartkey() # only if partkey and partkey.number are not null, send partkey.number self.replace('@', partkey and partkey.number) self.replace(u'¶', partkey and partkey.tocentry) if not '$' in self.formatted or not partkey or not partkey.titlecontents: # there is a $ left, but it should go away on preprocessing self.contents = [Constant(self.formatted)] return pieces = self.formatted.split('$') self.contents = [Constant(pieces[0])] for piece in pieces[1:]: self.contents += partkey.titlecontents self.contents.append(Constant(piece))
def isactive(self): "Check if the branch is active" if not self.branch in Options.branches: Trace.error('Invalid branch ' + self.branch) return True branch = Options.branches[self.branch] return branch.isselected()
def parseending(self, reader, process): "Parse until the current ending is found" if not self.ending: Trace.error('No ending for ' + unicode(self)) return while not reader.currentline().startswith(self.ending): process()
def process(self): "Set the correct script tag." self.type = self.header[2] if not self.type in TagConfig.script: Trace.error('Unknown script type ' + self.type) return self.output.settag(TagConfig.script[self.type], False)
def formatcontents(self): "Format the reference contents." formatkey = self.getparameter('LatexCommand') if not formatkey: formatkey = 'ref' self.formatted = '↕' if formatkey in StyleConfig.referenceformats: self.formatted = StyleConfig.referenceformats[formatkey] else: Trace.error('Unknown reference format ' + formatkey) self.replace('↕', self.direction) self.replace('#', '1') self.replace('on-page', Translator.translate('on-page')) partkey = self.destination.findpartkey() # only if partkey and partkey.number are not null, send partkey.number self.replace('@', partkey and partkey.number) self.replace('¶', partkey and partkey.tocentry) if not '$' in self.formatted or not partkey or not partkey.titlecontents: # there is a $ left, but it should go away on preprocessing self.contents = [Constant(self.formatted)] return pieces = self.formatted.split('$') self.contents = [Constant(pieces[0])] for piece in pieces[1:]: self.contents += partkey.titlecontents self.contents.append(Constant(piece))
def setcolumns(self, columns): "Process alignments for every column" if len(columns) != len(self.contents): Trace.error('Columns: ' + str(len(columns)) + ', cells: ' + str(len(self.contents))) return for index, cell in enumerate(self.contents): columns[index].set(cell)
def add(self, pieces): "Add a new set of alternative pieces." alternative = Declaration('#' + unicode(len(self.alternatives))) alternative.pieces = pieces self.alternatives.append(alternative) Trace.debug('Alternatives: ' + unicode(self)) return self
def checknext(self, token): "Check that the next token is the parameter." self.next() if self.currenttoken != token: Trace.error('Expected token ' + token + ', found ' + self.currenttoken) return False return True
def convert(self, image): "Convert an image to PNG" if not ImageConverter.active or Options.noconvert: return if image.origin.path == image.destination.path: return if image.destination.exists(): if image.origin.getmtime() <= image.destination.getmtime(): # file has not changed; do not convert return image.destination.createdirs() if Options.copyimages: Trace.debug('Copying ' + image.origin.path + ' to ' + image.destination.path) shutil.copy2(image.origin.path, image.destination.path) return converter, command = self.buildcommand(image) try: Trace.debug(converter + ' command: "' + command + '"') result = os.system(command.encode(sys.getfilesystemencoding())) if result != 0: Trace.error(converter + ' not installed; images will not be processed') ImageConverter.active = False return Trace.message('Converted ' + unicode(image.origin) + ' to ' + unicode(image.destination)) except OSError, exception: Trace.error('Error while converting image ' + unicode(image.origin) + ': ' + unicode(exception))
def convert(self, image): "Convert an image to PNG" if not ImageConverter.active or Options.noconvert: return if image.origin.path == image.destination.path: return if image.destination.exists(): if image.origin.getmtime() <= image.destination.getmtime(): # file has not changed; do not convert return image.destination.createdirs() if Options.copyimages: Trace.debug('Copying ' + image.origin.path + ' to ' + image.destination.path) shutil.copy2(image.origin.path, image.destination.path) return converter, command = self.buildcommand(image) try: Trace.debug(converter + ' command: "' + command + '"') result = os.system(command.encode(sys.getfilesystemencoding())) if result != 0: Trace.error(converter + ' not installed; images will not be processed') ImageConverter.active = False return Trace.message('Converted ' + str(image.origin) + ' to ' + str(image.destination)) except OSError as exception: Trace.error('Error while converting image ' + str(image.origin) + ': ' + str(exception))
def write(self, strings): "Write a list of strings" for string in strings: if not isinstance(string, basestring): Trace.error('Not a string: ' + unicode(string) + ' in ' + unicode(strings)) return self.writestring(string)
def current(self): "Return the current character, assuming we are not out." if self.pos == len(self.reader.currentline()): return '\n' if self.pos > len(self.reader.currentline()): Trace.error('Out of the line ' + self.reader.currentline() + ': ' + unicode(self.pos)) return '*' return self.reader.currentline()[self.pos]
def process(self): "Process contents" self.type = self.header[2] if not self.type in StyleConfig.quotes: Trace.error('Quote type ' + self.type + ' not found') self.html = ['"'] return self.html = [StyleConfig.quotes[self.type]]
def process(self): "Parse the type of bar" self.type = self.header[1] if not self.type in TagConfig.barred: Trace.error('Unknown bar type ' + self.type) self.output.tag = 'span' return self.output.tag = TagConfig.barred[self.type]
def process(self): "Parse the type of family" self.type = self.header[1] if not self.type in TagConfig.family: Trace.error('Unrecognized family ' + type) self.output.tag = 'span' return self.output.tag = TagConfig.family[self.type]
def usage(): "Show command line help." Trace.error('Usage: loremipsumize.py filein [fileout]') Trace.error('Mask your document using nonsensical words (Lorem Ipsum).') Trace.error('Part of the eLyXer package (http://elyxer.nongnu.org/).') Trace.error(' Options:') Trace.error(' --help: show this message and quit.') return
def parse(self, tok): "Parse a whole file using a tokenizer." next(tok) filedecl = self.declarations['$file'] result = filedecl.match(tok) if not result: Trace.error('Actual file does not match $file.') return
def parsesection(self, line): "Parse a section header" if not line.endswith(']'): Trace.error('Incorrect section header ' + line) return name = line[1:-1] self.section = name self.objects[name] = dict()
def readformat(self, file, format, bytes): "Read any format from elyxer.file" read = file.read(bytes) if read == '' or len(read) < bytes: Trace.error('EOF reached') return 0 tuple = struct.unpack(format, read) return tuple[0]
def checktag(self): "Check that the tag is valid." if not self.tag: Trace.error('No tag in ' + unicode(container)) return False if self.tag == '': return False return True
def parsebit(self, pos): "Parse the parameter: #n." if not pos.checkskip('#'): Trace.error('Missing parameter start #.') return self.number = int(pos.skipcurrent()) self.original = '#' + str(self.number) self.contents = [TaggedBit().constant('#' + str(self.number), 'span class="unknown"')]
def checktag(self): "Check that the tag is valid." if not self.tag: Trace.error('No tag in ' + str(container)) return False if self.tag == '': return False return True
def extractfromstring(self, container): "Extract the first word from elyxer.a string container." if not ' ' in container.string: Trace.error('No space in string ' + container.string) return container split = container.string.split(' ', 1) container.string = split[1] return Constant(split[0])
def setcolumns(self, columns): "Process alignments for every column" if len(columns) != len(self.contents): Trace.error('Columns: ' + unicode(len(columns)) + ', cells: ' + unicode(len(self.contents))) return for index, cell in enumerate(self.contents): columns[index].set(cell)
def parse(self, tok): "Parse a whole file using a tokenizer." tok.next() filedecl = self.declarations['$file'] result = filedecl.match(tok) if not result: Trace.error('Actual file does not match $file.') return
def parsebit(self, pos): "Parse the symbol" if pos.current() in FormulaSymbol.unmodified: self.addsymbol(pos.current(), pos) return if pos.current() in FormulaSymbol.modified: self.addsymbol(FormulaSymbol.modified[pos.current()], pos) return Trace.error('Symbol ' + pos.current() + ' not found')
def isempty(self): "Find out if the ERT is empty or not." if len(self.contents) == 0: return True if len(self.contents) > 1: Trace.error('Unknown ERT length 2') return False texcode = self.contents[0] return len(texcode.contents) == 0
def parselstset(self, reader): "Parse a declaration of lstparams in lstset." paramtext = self.extractlstset(reader) if not '{' in paramtext: Trace.error('Missing opening bracket in lstset: ' + paramtext) return lefttext = paramtext.split('{')[1] croppedtext = lefttext[:-1] LstParser.globalparams = self.parselstparams(croppedtext)
def extractlstset(self, reader): "Extract the global lstset parameters." paramtext = '' while not reader.finished(): paramtext += reader.currentline() reader.nextline() if paramtext.endswith('}'): return paramtext Trace.error('Could not find end of \\lstset settings; aborting')
def translatetemplate(self, template): "Translate a complete template into a list of contents." pos = TextPosition(template) part = BibPart(self.parser.tags).parse(pos) for variable in part.searchall(BibVariable): if variable.empty(): Trace.error('Error parsing BibTeX template for ' + str(self) + ': ' + str(variable) + ' is empty') return [part]
def popending(self, expected=None): "Pop the ending found at the current position" if self.isout() and self.leavepending: return expected ending = self.endinglist.pop(self) if expected and expected != ending: Trace.error('Expected ending ' + expected + ', got ' + ending) self.skip(ending) return ending
def main(): "Main function, called if invoked from elyxer.the command line" args = sys.argv Options().parseoptions(args) if len(args) != 1: Trace.error('Usage: math2html.py escaped_string') exit() result = math2html(args[0]) Trace.message(result)
def parsetext(self, pos): "Parse a text parameter." self.factory.clearskipped(pos) if not self.factory.detecttype(Bracket, pos): Trace.error('No text parameter for ' + self.command) return None bracket = Bracket().setfactory(self.factory).parsetext(pos) self.add(bracket) return bracket