def _maybe_upgrade_database(version): # Quick schema migration. More to do later. version = SW.Version(str(version)) if version <= SW.Version("0.4"): connection.executescript( """ ALTER TABLE topic ADD COLUMN order_passages_by varchar; UPDATE master_topic_record SET schema_version = '%s'; """ % _CURRENT_VERSION) if version < SW.Version("0.4.6"): print "Upgrading to include look" connection.executescript( """ ALTER TABLE topic ADD COLUMN tag_colour integer; ALTER TABLE topic ADD COLUMN tag_look integer; UPDATE topic SET tag_colour = 0; UPDATE topic SET tag_look = NULL; UPDATE master_topic_record SET schema_version = '%s'; """ % _CURRENT_VERSION) elif version < SW.Version("0.4.6.1"): # temporary upgrade bit, remove later print "Upgrading to include look" connection.executescript( """ ALTER TABLE topic ADD COLUMN tag_colour integer; UPDATE topic SET tag_colour = 0; UPDATE topic SET tag_look = NULL; UPDATE master_topic_record SET schema_version = '%s'; """ % _CURRENT_VERSION)
def upgrade(self, config_parser, version_from): dprint(MESSAGE, "Upgrading from", version_from.getText()) if version_from <= SW.Version("0.3"): self._upgrade_03_to_04(config_parser) if version_from < SW.Version("0.4.1"): self._upgrade_04_to_041(config_parser) if version_from < SW.Version("0.4.2"): self._upgrade_041_to_042(config_parser) if version_from < SW.Version("0.5.2"): self._upgrade_042_to_052(config_parser)
def make_manager(self, path): markup_inserter = MarkupInserter(self) markup = SW.MyMarkup(markup_inserter, SW.FMT_HTMLHREF) #, SW.ENC_HTML) #markup = SW.MarkupFilterMgr(SW.FMT_HTMLHREF, SW.ENC_HTML) markup.thisown = False # don't augment home path mgr = SW.Mgr(path, True, markup, False, False) return mgr
def _handle(self, d, frame, href, *args): url = SW.URL(str(href)) protocol = url.getProtocol() # don't decode if no protocol, or : in decoded may become the protocol if protocol: href = SW.URL.decode(str(href)).c_str() url = SW.URL(href) protocol = url.getProtocol() if protocol in d: d[protocol](frame, href, url, *args) else: dprint(WARNING, "Protocol %s has no handler" % protocol, href)
def on_genbook_click(frame, href, url): if frame != guiconfig.mainfrm.genbooktext: frame = guiconfig.mainfrm.genbooktext if url is None: url = SW.URL(href) host = to_unicode(url.getHostName(), frame.reference.module) if host == "previous": frame.chapter_back() elif host == "next": frame.chapter_forward() elif host.startswith("parent"): frame.go_to_parent(int(host[6:])) else: key = TK(frame.book.mod.getKey(), frame.book.mod) path = to_unicode(url.getPath(), frame.reference.module) ref = u"/%s" % host if path: ref += "/%s" % path key.text = ref frame.go_to_key(key)
def subst(match): if (is_bible or match.group(1)): if match.group(2).startswith("%3F"): url = SW.URL("bible:" + SW.URL.decode(str(match.group(2))).c_str()) values = url.getParameterValue("values") references = VerseList([ url.getParameterValue("val%s" % value) for value in range(int(values)) ]) else: reference_text = SW.URL.decode(str(match.group(2))).c_str() references = VerseList(reference_text) else: # our closing </a>? if not is_bible and in_ref[0] and match.group(4): in_ref[0] = False return "</span>%s" % match.group(4) return match.group(0) for item in v: for i in item: if references.VerseInRange(i): if is_bible: # wrap the contents of the <a> in formatting return '%s<a name="highlight"></a><span class="search_highlight">%s</span>%s' % match.group(1, 4, 5) else: # start the formatting, to be completed with # the </a> tag handling above in_ref[0] = True return '%s<a name="highlight"></a><span class="search_highlight">' % \ match.group(1) return match.group(0)
def has_feature(self, feature, module=None): if module is not None: oldmod = self.mod try: self.SetModule(module, notify=False) return self.has_feature(feature) finally: self.SetModule(oldmod, notify=False) if not self.mod: return False if self.features is None: self.features = [] mod = self.mod map = mod.getConfigMap() feature_buf = SW.Buf("Feature") featureBegin = map.lower_bound(feature_buf) featureEnd = map.upper_bound(feature_buf) while featureBegin != featureEnd: v = featureBegin.value() self.features.append(v[1].c_str()) featureBegin += 1 return feature in self.features
def on_headings_hover(frame, href, url, element, x, y): if url is None: url = SW.URL(href) ref = url.getHostName() # print ref frame.show_tooltip(ChapterHeadingsTooltipConfig(ref))
def get_config(self, mod): pp = mod.getConfigEntry("PrefixPath") pp += "mods.d/%s.conf" % mod.Name().lower() # make sure it exists os.stat(pp) return SW.Config(pp)
def find_languages(is_release=False): languages = {} for item in os.listdir("locales"): if "en_au" in item.lower() and is_release: continue if os.path.isdir("locales/" + item) and item != "locales.d" and \ os.path.exists("locales/%s/locale.conf" % item): conf = SW.Config("locales/%s/locale.conf" % item) language = conf.get("Language", "Description") or item locale = conf.get("SWORD", "locale") or "bpbible" abbrev_locale = conf.get("SWORD", "abbreviations") or locale locale_conf = SW.Locale("locales/%s/locale.conf" % item) languages[item] = language, locale, abbrev_locale, locale_conf return languages
def GetFootnoteData(self, mod, passage, number, field): if mod != self.mod: if not isinstance(mod, SW.Module): mod = self.parent.get_module(mod) if mod is None: return None else: mod = self.mod vk = SW.Key(passage) mod.SetKey(vk) #set passage mod.RenderText() # force entry attributes to get set data = mod.getEntryAttributesMap()[SW.Buf("Footnote")] \ [SW.Buf(number)][SW.Buf(field)].c_str() # put it through the render filter before returning it return mod.RenderText(data).decode("utf8", "replace")
def find_passage_study_url(href): try: p = href[href.index("passagestudy.jsp"):] except ValueError: print "Unhandled bpbible link", href return return p, SW.URL( p.replace(":", '%3A').replace(' ', '%20').replace('/', '%2F'))
def load(self, paths=()): config_parser = RawConfigParser() loaded = config_parser.read(self.write_path) loaded += config_parser.read(paths) if config_parser.has_option("Internal", "version"): version = config_parser.get("Internal", "version") elif loaded: version = "0.3" else: version = CONFIG_VERSION if SW.Version(version) < SW.Version(CONFIG_VERSION): self.upgrade(config_parser, SW.Version(version)) for section_name in config_parser.sections(): if section_name not in self.sections: dprint(WARNING, "Skipping unknown section '%s'" % section_name) continue section = self.sections[section_name] for option in config_parser.options(section_name): if option not in section.items: dprint( WARNING, "Skipping unknown item '%s.%s'" % (section_name, option)) continue if option in section.lazy_items: section.lazy_items.remove(option) type_reader = { str: config_parser.get, bool: config_parser.getboolean, int: config_parser.getint, float: config_parser.getfloat, "pickle": lambda x, y: pickle.loads(config_parser.get(x, y)) }[section.item_types[option]] section[option] = type_reader(section_name, option) self["Internal"]["version"] = CONFIG_VERSION
def get_headings(self, ref, mod=None): """Gets an array of the headings for the current verse. Must have just called RenderText on the verse you want headings for""" mod = mod or self.mod heading = SW.Buf("Heading") preverse = SW.Buf("Preverse") interverse = SW.Buf("Interverse") canonical = SW.Buf("canonical") headings = [] heading_types = [preverse, interverse] attrmap = mod.getEntryAttributesMap() #[SW.Buf("Heading") if heading in attrmap: h = attrmap[heading] if preverse in h: i = 0 p = h[preverse] while True: is_canonical = "false" i_buf = SW.Buf(str(i)) # try to see if this is a canonical heading # unfortunately, if there happens to be a interverse # heading after a canonical heading, it will overwrite it # so we may not get the correct answer. This oughtn't to # matter overly much if i_buf in h: attributes = h[i_buf] if (canonical in attributes and attributes[canonical].c_str() == "true"): is_canonical = "true" if i_buf in p: headings.append((p[i_buf].c_str(), is_canonical)) else: break i += 1 if not headings: dprint(WARNING, "no heading found for", ref) return headings
def make_osis(): osisrenderer = osisparser.OSISRenderer() items.append(osisrenderer) osis = SW.PyOSISHTMLHREF(osisrenderer) osis.thisown = False osis.removeTokenSubstitute("lg") osis.removeTokenSubstitute("/lg") return osisrenderer, osis
def unlock(self, mod, key): assert self.get_cipher_code(mod) != None cm = mod.getConfigMap() cm[SW.Buf("CipherKey")] = SW.Buf(key) mgr = self.get_mgr(mod) mgr.setCipherKey(mod.Name(), key) conf = self.get_config(mod) conf.set(mod.Name(), "CipherKey", key) conf.Save() # send a refresh through for this book # TODO: do this better self.observers(self.mod) conf = self.get_config(mod) if conf.get(mod.Name(), "CipherKey") != key: raise FileSaveException( _("Couldn't save cipher key. You will have to set it again when you restart" ))
def GetChapter(self, ref, specialref="", specialtemplate=None, context="", raw=False): self.vk.setText(to_str(ref, self.mod)) #get first ref text = self.vk.getText() match = re.match("([\w\s]+) (\d+):(\d+)", text) if match: book, chapter, verse = match.group(1, 2, 3) # include introductions - book introduction if necessary ref = "%s %s" % (book, chapter) text = "%s %s:0-%s %s" % (book, chapter, book, chapter) vk = SW.VerseKey() vk.Headings(1) list = vk.ParseVerseList(text, "", True) if chapter == "1": vk.setText("%s 0:0" % book) list.add(vk) #text = "%s 0:0-%s %s" % (book, book, chapter) if book == "Genesis": vk.Testament(0) list.add(vk) vk.Testament(1) list.add(vk) elif book == "Matthew": # set it to 0 first so that we come back to the testament # heading vk.Testament(0) vk.Testament(2) list.add(vk) list.sort() else: dprint(ERROR, "Couldn't parse verse text", text) return "" return self.GetReference(ref, specialref, specialtemplate, context, raw=raw, headings=True, verselist=list)
def insert_footnotes(match): #print "Inserting footnotes", match href = match.group(1) url = SW.URL(href.encode("utf8")) ftype = url.getParameterValue("type") #x or n value = url.getParameterValue("value") #number footnote in verse if ((not ftype) or (not value)): dprint(WARNING, "Not type or value in showNote", href) return "" module = biblemgr.get_module(url.getParameterValue("module")) passage = url.getParameterValue("passage") back_ref = VK(passage).getOSISRef() user_ref = book_fix(internal_to_user(passage)) if not passage or not module: print "No passage/module?" return "" id = "footnote_data_%s_%s" % (back_ref, value) #print passage, id if ftype in ("n", "x"): data = sword_book.GetFootnoteData(module, passage, value, "body") if footnotes[ftype] and footnotes[ftype][-1][0] == back_ref: footnotes_group = footnotes[ftype][-1] else: footnotes_group = [ back_ref, "<div class='verse_footnotes footnote_%s' id='verse_footnote_%s_%s'>%s for " "<a href='#%s_start'>%s</a>%%s</div>" % (ftype, back_ref, ftype, footnote_types[ftype], back_ref, user_ref) ] footnotes[ftype].append(footnotes_group) footnotes_group.append( "<div class='footnote_data' id='%s'><span class='footnote_marker'>%s</span>: %s</div>" % (id, match.group(3), data)) else: print "Footnote type was", ftype id = "verse_footnote_%s_%s" % (back_ref, ftype) return 'href="#%s"%s' % (id, match.group(2))
def write_osis_ref(self, ref, node, si, parse_children): items = [] cnt = 0 for item in ref.split(" "): if "-" in item: assert item.count("-") == 1, item start, end = item.split("-") vk = SW.VerseKey(start, end) while vk.Error() == '\x00': items.append(vk.getOSISRef()) vk.increment(1) else: items.append(item) refs = u' '.join(items) refs = refs.encode("utf8").replace(".", self.FIELD_SEPARATOR) self.write_field(node, si, fields.RefField, refs, parse_children)
def items(self): for item, values in sorted(self.iteritems(), key=lambda (key, value): key): for value in values: yield SW.Buf(item), SW.Buf(value)
def make_thml(): thmlrenderer = thmlparser.THMLRenderer() items.append(thmlrenderer) thml = SW.PyThMLHTMLHREF(thmlrenderer) thml.thisown = False return thmlrenderer, thml
return markups[markup] return None def make_thml(): thmlrenderer = thmlparser.THMLRenderer() items.append(thmlrenderer) thml = SW.PyThMLHTMLHREF(thmlrenderer) thml.thisown = False return thmlrenderer, thml def make_osis(): osisrenderer = osisparser.OSISRenderer() items.append(osisrenderer) osis = SW.PyOSISHTMLHREF(osisrenderer) osis.thisown = False osis.removeTokenSubstitute("lg") osis.removeTokenSubstitute("/lg") return osisrenderer, osis osisrenderer, osis = make_osis() thmlrenderer, thml = make_thml() osis2 = SW.OSISHTMLHREF() thml2 = SW.ThMLHTMLHREF() items.extend([osis2, thml2])
btext.append(a) seen.add(a) verses.update(spl) return [x for x in btext if x not in removals] class SearchException(Exception): pass class Cancelled(Exception): pass vk = SW.VerseKey() def printx(x): print x return True class BadBook(Exception): def __init__(self, index, errors): errors = [ _("A problem was detected with this book while indexing it:") ] + list(errors) + [ '', _("Check whether there is a newer version of this book which " "might fix this problem.")
def start_note(self, xmltag): self.did_xref = False type = xmltag.getAttribute("type") footnoteNumber = xmltag.getAttribute("swordFootnote") if not type: print "Not type - module bug", xmltag.toString() type = "missing" if not type or not footnoteNumber: if type != "x-strongsMarkup": print "FAILED", xmltag.toString() self.success = SW.INHERITED return was_xref = type in ("crossReference", "x-cross-ref") footnote_type = "n" if was_xref: footnote_type = "x" expand_crossref = filterutils.filter_settings["footnote_ellipsis_level"] footnotes = SW.Buf("Footnote") refList = SW.Buf("refList") n = SW.Buf("n") number = SW.Buf(footnoteNumber) map = self.u.module.getEntryAttributesMap() footnote = map[footnotes][number] if n in footnote: footnote_char = footnote[n].c_str() else: if was_xref: footnote_char = "x" else: footnote_char = "n" refs_to_expand = None if expand_crossref: try: refs_to_expand = footnote[refList].c_str() except IndexError: dprint(WARNING, "Error getting Footnote '%s' refList" % footnoteNumber) if refs_to_expand: self.u.inXRefNote = True self.buf += filterutils.ellipsize( refs_to_expand.split(";"), self.u.key.getText(), int(filterutils.filter_settings["footnote_ellipsis_level"]) ) else: c = "footnote footnote_%s" % type self.buf += "<a class=\"%s\" href=\"newbible://content/passagestudy.jsp?action=showNote&type=%c&value=%s&module=%s&passage=%s\">%s</a>" % ( c, footnote_type, SW.URL.encode(footnoteNumber).c_str(), SW.URL.encode(self.u.version.c_str()).c_str(), SW.URL.encode(self.u.key.getText()).c_str(), footnote_char ) self.did_xref = True self.u.suspendLevel += 1 self.u.suspendTextPassThru = self.u.suspendLevel
print module_dir result = driver.createModule(module_dir) assert result == '\x00', \ "Failed creating module" module = driver(module_dir) assert module.isWritable(), "MODULE MUST BE WRITABLE" for key in keys: from swlib.pysw import VerseList key = VerseList(key)[0] lower_bound = key.LowerBound().getText() key_text = "This is %s." % key.getRangeText() module.setKey(SW.VerseKey(lower_bound)) module.setEntry(key_text) for linked_key in [key_.getText() for key_ in key][1:]: module.setKey(SW.VerseKey(linked_key)) module.linkEntry(SW.VerseKey(lower_bound)) conf_file = items["bible"][4] f = open("mods.d/test_bad.conf", "w") f.write(conf_file + "\ntest") f.close() zip = zipfile.ZipFile("test_bad.zip", "w") zip.write("mods.d/test_bad.conf") zip.close()
def start_q(self, tag): style, quote_mapping = quotes.get_quotes() #print "Q", tag.toString() type = tag.getAttribute("type"); who = tag.getAttribute("who"); tmp = tag.getAttribute("level"); level = int(tmp) if tmp else 1 mark = tag.getAttribute("marker"); # open <q> or <q sID... /> if ((not tag.isEmpty() and not tag.isEndTag()) or (tag.isEmpty() and tag.getAttribute("sID"))): # if <q> then remember it for the </q> if not tag.isEmpty(): self._quotes.append(tag.toString()) # Do this first so quote marks are included as WoC if (who == "Jesus"): self.write("<span class='WoC'>") # first check to see if we've been given an explicit mark if mark is not None: self.write(mark) # alternate " and ' elif (self.u.osisQToTick): self.write('"' if (level % 2) else '\'') if tag.getAttribute("sID"): qID = tag.getAttribute("sID").replace(".", "_") d = quote_mapping.get(qID, "") if not d: dprint(WARNING, "No who found for qID", qID) self.write_quote(qID, d, True) self._quotes_data.append((qID, d)) else: #print "non-sid Start", tag.toString() pass # close </q> or <q eID... /> elif ((tag.isEndTag()) or (tag.isEmpty() and tag.getAttribute("eID"))): # if it is </q> then pop the stack for the attributes if (tag.isEndTag() and self._quotes): tagData = self._quotes.pop() qTag = SW.XMLTag(tagData) type = qTag.getAttribute("type"); who = qTag.getAttribute("who"); tmp = qTag.getAttribute("level"); level = int(tmp) if tmp else 1 mark = qTag.getAttribute("marker"); qID = tag.getAttribute("eID") if qID: qID = qID.replace(".", "_") if not self._quotes_data: dprint(ERROR, "Quotes data empty", qID, self.u.key.getText()) else: d = self._quotes_data.pop() if d[0] != qID: dprint(ERROR, "Mismatching closing quotes", d, qID) self.write_quote(d[0], d[1], False) #else: # print tag.toString() # first check to see if we've been given an explicit mark if mark is not None: self.write(mark) # finally, alternate " and ', if config says we should supply a mark elif (self.u.osisQToTick): self.write('"' if (level % 2) else '\'') # Do this last so quote marks are included as WoC if (who == "Jesus"): self.write("</span>")
def get_document(self, path): module_name, rest = path.split("/", 1) ref, direction = rest.rsplit("/", 1) assert direction in ("next", "previous") dir = {"next": 1, "previous": -1}[direction] book = biblemgr.get_module_book_wrapper(module_name) mod = book.mod no_more = False if book.is_verse_keyed: vk = VK(ref, headings=not book.chapter_view) if book.chapter_view: vk.chapter += dir if vk.Error(): print "No more in that direction", dir no_more = True else: # go back just a little, so that when we go forward on the module # we won't overshoot... (at least, that is our plan - we hope it # won't be baffled...) vk.Verse(vk.Verse() - dir) if vk.Error(): print "VK had an error taking away a verse", dir if not no_more: old_mod_skiplinks = mod.getSkipConsecutiveLinks() mod.setSkipConsecutiveLinks(True) try: vk.Persist(1) mod.setKey(vk) #print repr(mod.Error()) mod.increment(dir) if mod.Error() != '\x00': print "Mod had an error" no_more = True else: if book.chapter_view: new_ref = vk.get_chapter_osis_ref() else: new_ref = vk.getOSISRef() finally: mod.setKey(SW.Key()) mod.setSkipConsecutiveLinks(old_mod_skiplinks) elif book.is_dictionary: # XXX: Would using an index rather than a reference (as the XUL code did) be more efficient? book.snap_text(ref) book.mod.increment(dir) if mod.Error() == '\x00' and book.mod.getKey().getText(): new_ref = to_unicode(mod.getKey().getText(), mod) else: no_more = True elif book.is_genbook: ref = "/" + ref tk = book.GetKey() tk.Persist(1) assert tk.thisown newtk = book.GetKey() newtk.thisown = True mod.setKey(tk) print "Getting next for", ref tk.set_text(ref) print tk.getText() if mod.Error() != '\x00': print "Error on initial set?" mod.increment(dir) if mod.Error() == '\x00' and tk.getText(): new_ref = to_unicode(tk.getText(), mod)[1:] # trim off the leading / else: no_more = True mod.setKey(newtk) else: print "Book type not handled", module_name if no_more: message = (_("You are at the start of this book.") if dir == -1 else _("You are at the end of this book.")) class_name = "book-%s" % ("start" if dir == -1 else "end") return ''' <div class="page_segment" empty="true"> <div class='no_more_text %(class_name)s'> %(message)s </div> </div>''' % locals() return '<div class="page_segment">%(content)s%(timer)s</div>' % self._get_document_parts_for_ref( module_name, new_ref, do_current_ref=False)
def is_bold(self, item): module = self.modules[item] key = to_str(self.key, module) k = SW.Key(key) return module.hasEntry(k)
def get_parallel_text(self, ref): vk = SW.VerseKey() verselist = vk.ParseVerseList(to_str(ref), "", True) items = [] text = ["<table class='parallel_view'>", "<tr>"] for item in self.book.GetModules(): name = item.Name() if name in verse_comparison_settings["comparison_modules"]: items.append((item, list( self.book.GetReference_yield( verselist, module=item, max_verses=176, skip_linked_verses=False)))) text.append(u"<th>%s</th>" % process_html_for_module( item, u"<b><a href='%s:%s'>" "%s</a></b>" % (BIBLE_VERSION_PROTOCOL, name, name))) text.append("</tr>") # if we have no bibles to compare, return the empty string if not items: return "" rows = [] was_clipped = False try: self.book.templatelist.append(config.parallel_template) while True: text.append("<tr>") for module, refs in items: if not refs: text.append("</tr>") break body_dict, headings = refs.pop(0) if not body_dict: was_clipped = True # remove opening row text.pop() break text_direction = get_module_css_text_direction(module) text.append( u'<td class="parallel_verse" module="%s" dir="%s">' % (module.Name(), text_direction)) t = "" for heading_dict in headings: t += biblemgr.bible.templatelist[-1].\ headings.safe_substitute(heading_dict) t += biblemgr.bible.templatelist[-1].\ body.safe_substitute(body_dict) t = process_html_for_module(module, t) text.append(t) text.append("</td>") else: text.append("</tr>") continue break finally: self.book.templatelist.pop() text.append("</table>") if was_clipped: text.append(config.MAX_VERSES_EXCEEDED() % 177) return ''.join(text)
def GetReference_yield(self, verselist, max_verses=177, raw=False, stripped=False, module=None, exclude_topic_tag=None, display_tags=True, skip_linked_verses=True): """GetReference_yield: yield the body dictionary and headings dictinoary for each reference. Preconditions: one of module or self.mod is not None verselist is valid""" #only for bible keyed books verselist.setPosition(TOP) verselist.Persist(1) u_vk = pysw.UserVK() u_vk.Headings(1) versekey = SW.VerseKey() versekey.Headings(1) mod = module or self.mod old_mod_skiplinks = mod.getSkipConsecutiveLinks() mod.setSkipConsecutiveLinks(True) mod.SetKey(verselist) verses_left = max_verses render_text, render_start, render_end = self.get_rendertext(mod) if render_start: render_start() try: incrementer = mod if skip_linked_verses else verselist while not self.has_error(incrementer): if verses_left == 0: yield None, None break if not skip_linked_verses: mod.SetKey(verselist) key = mod.getKey() #versekey = VK.castTo(key) versekey.setText(key.getText()) #if(self.headings): # versekey.Headings(1) osisRef = versekey.getOSISRef() internal_reference = versekey.getText() rawentry = mod.getRawEntryBuf() if skip_linked_verses and not rawentry.length(): # don't include empty text; typically this may be at the # start of the chapter or something... incrementer.increment(1) continue start_verse = end_verse = versekey.Verse() # look forwards and backwards to see what the linked verse # number is (e.g. 3-5). Note: currently this won't cross # chapter boundaries vk = versekey.clone() vk = versekey.castTo(vk) vk.thisown = True vk.Headings(0) while (vk.Error() == '\x00' and vk.Chapter() == versekey.Chapter() and mod.isLinked(vk, versekey)): end_verse = vk.Verse() vk.increment(1) vk.copyFrom(versekey) vk.Headings(0) # hopefully we won't see anything backwards, but it is # possible (i.e. if we start in the middle of a linked # verse while (vk.Error() == '\x00' and vk.Chapter() == versekey.Chapter() and mod.isLinked(vk, versekey)): start_verse = vk.Verse() vk.decrement(1) if start_verse == end_verse: verse = "%d" % start_verse else: verse = "%d-%d" % (start_verse, end_verse) u_vk.setText(internal_reference) if internal_reference.endswith(":0"): if start_verse != end_verse: print "WARNING: unhandled linked verse with verse 0" if versekey.Chapter() == 0: reference = u_vk.getBookName() else: reference = u_vk.get_book_chapter() else: reference = u_vk.get_book_chapter() reference += ":" + verse body_dict = dict( # text comes later versenumber=process_digits(verse, userOutput=True), chapternumber=process_digits(str(versekey.Chapter()), userOutput=True), booknumber=ord(versekey.Book()), bookabbrev=versekey.getBookAbbrev(), bookname=versekey.getBookName(), reference=reference, internal_reference=internal_reference, osisRef=osisRef, ) # usually RenderText flushes this out, but we haven't called # that yet - but we definitely don't want extraneous headings mod.getEntryAttributesMap().clear() # we want to do our pre-verse content first, but we can't # without running it through the optionFilter first. # we'll then have to run it through again after, otherwise our # entryattributes may go walkabout if raw: rawentry_str = rawentry.c_str() mod.optionFilter(rawentry, versekey) if raw: option_filtered = rawentry.c_str() headings = self.get_headings(internal_reference, mod) #versekey = VK.castTo(key) heading_dicts = [] raw_headings = [] for heading, canonical in headings: # the new-style pre-verse content lives wrapped up in # <div>'s - it will contain the <title>, but the div will # be stripped out. # the old-style pre-verse content lives in <title>'s, # which will also be stripped out. Unfortunately, it isn't # that easy to tell whether it did have a title, so we # employ a heuristic - if it starts with an <, it is a new # one... nh = heading.startswith("<") if stripped: heading = mod.StripText(heading).decode( "utf8", "replace") else: heading = render_text(heading).decode( "utf8", "replace") if not nh: cls = " canonical" if (canonical and canonical == "true") else "" heading = '<h2 class="heading%s">%s</h2>\n' % (cls, heading) if raw: raw_headings.append(heading) heading_dict = dict(heading=heading, canonical=canonical) heading_dict.update(body_dict) heading_dicts.append(heading_dict) if stripped: text = mod.StripText(rawentry.c_str(), rawentry.length()).decode( "utf-8", "replace") else: # we can't use rawentry due to a static local buffer in # swmodule.c; breaks gospel harmonies text = ( render_text( #rawentry.c_str(), rawentry.length() ).decode("utf8", "replace")) # get our actual text if raw: text = self.process_raw(rawentry_str, text, versekey, mod, raw_headings, option_filtered) user_comments = self.get_user_comments(osisRef, versekey) # XXX: This needs to be done better than this. Move into # subclass somehow. if isinstance(self, Bible) and display_tags: tags = self.insert_tags(osisRef, versekey, exclude_topic_tag) else: tags = "" body_dict.update( dict(text=text, tags=tags, usercomments=user_comments)) yield body_dict, heading_dicts incrementer.increment(1) verses_left -= 1 finally: mod.setKey(SW.Key()) mod.setSkipConsecutiveLinks(old_mod_skiplinks) self.end_of_render = "" if render_end: self.end_of_render = render_end()