| 1 |
|
| 2 |
import re |
| 3 |
import unicodedata |
| 4 |
import os |
| 5 |
|
| 6 |
from functools import cmp_to_key |
| 7 |
from glob import glob |
| 8 |
from operator import itemgetter |
| 9 |
|
| 10 |
from lxml import etree |
| 11 |
|
| 12 |
from . import NAMES, DATES, NUMBERS, PRIMARY_DIALECTS, LANGUAGE_NAMES |
| 13 |
from .source import VariableError, DateRange, LiteralDate |
| 14 |
from .string import String, join, normalize_seam |
| 15 |
|
| 16 |
|
| 17 |
# Base class |
| 18 |
|
| 19 |
class SomewhatObjectifiedElement(etree.ElementBase): |
| 20 |
nsmap = {'cs': 'http://purl.org/net/xbiblio/csl', |
| 21 |
'xml': 'http://www.w3.org/XML/1998/namespace'} |
| 22 |
|
| 23 |
# TODO: what about multiple instances of the same name? |
| 24 |
def __getattr__(self, name): |
| 25 |
return self.find('cs:' + name, self.nsmap) |
| 26 |
|
| 27 |
|
| 28 |
class CitationStylesElement(SomewhatObjectifiedElement): |
| 29 |
_default_options = {# global options |
| 30 |
'initialize-with-hyphen': 'true', |
| 31 |
'page-range-format': None, |
| 32 |
'demote-non-dropping-particle': 'display-and-sort', |
| 33 |
|
| 34 |
# inheritable name(s) options |
| 35 |
'and': None, |
| 36 |
'delimiter-precedes-et-al': 'contextual', |
| 37 |
'delimiter-precedes-last': 'contextual', |
| 38 |
'et-al-min': 0, |
| 39 |
'et-al-use-first': 1, |
| 40 |
'et-al-subsequent-min': 0, |
| 41 |
'et-al-subsequent-use-first': 1, |
| 42 |
'et-al-use-last': 'false', |
| 43 |
'initialize-with': None, |
| 44 |
'name-as-sort-order': None, |
| 45 |
'sort-separator': ', ', |
| 46 |
|
| 47 |
'name-form': 'long', |
| 48 |
'name-delimiter': ', ', |
| 49 |
'names-delimiter': ''} |
| 50 |
|
| 51 |
def get_root(self): |
| 52 |
return self.getroottree().getroot() |
| 53 |
|
| 54 |
def xpath_search(self, expression): |
| 55 |
return self.xpath(expression, namespaces=self.nsmap) |
| 56 |
|
| 57 |
@property |
| 58 |
def loc(self): |
| 59 |
full_xpath = self.getroottree().getpath(self) |
| 60 |
xpath = '' |
| 61 |
tree = [] |
| 62 |
for i, node in enumerate(full_xpath.split('/')[1:]): |
| 63 |
xpath += '/' + node |
| 64 |
element = self.xpath(xpath)[0] |
| 65 |
namespace, tag = element.tag.split('}', 1) |
| 66 |
attribs = ''.join(' {}="{}"'.format(key, value) |
| 67 |
for key, value in element.attrib.items()) |
| 68 |
tree.append('{:>4}: {}<{}{}>'.format(element.sourceline, |
| 69 |
i * ' ', tag, attribs)) |
| 70 |
print('\n'.join(tree)) |
| 71 |
|
| 72 |
def get_option(self, name): |
| 73 |
return self.get(name, self._default_options[name]) |
| 74 |
|
| 75 |
def get_macro(self, name): |
| 76 |
expression = "cs:macro[@name='{}'][1]".format(name) |
| 77 |
return self.get_root().xpath_search(expression)[0] |
| 78 |
|
| 79 |
def get_layout(self): |
| 80 |
return self.xpath_search('./ancestor-or-self::cs:layout[1]')[0] |
| 81 |
|
| 82 |
def get_formatter(self): |
| 83 |
if isinstance(self.get_root(), Locale): |
| 84 |
return self.get_root().style.formatter |
| 85 |
else: |
| 86 |
return self.get_root().formatter |
| 87 |
|
| 88 |
def preformat(self, text): |
| 89 |
return self.get_formatter().preformat(text) |
| 90 |
|
| 91 |
def unicode_character(self, name): |
| 92 |
return self.preformat(unicodedata.lookup(name)) |
| 93 |
|
| 94 |
def render(self, *args, **kwargs): |
| 95 |
return self.markup(self.process(*args, **kwargs)) |
| 96 |
|
| 97 |
# TODO: Locale methods |
| 98 |
def get_term(self, name, form=None, fallback_locale=True, zero_padded=False): |
| 99 |
lg_key = "{http://www.w3.org/XML/1998/namespace}lang" |
| 100 |
if isinstance(self.get_root(), Locale): |
| 101 |
return self.get_root().get_term(name, form) |
| 102 |
else: |
| 103 |
locales = self.get_root().locales |
| 104 |
if not fallback_locale and len(locales) > 1: |
| 105 |
main_locale = locales[0] |
| 106 |
main_lg = main_locale.attrib.get(lg_key, None) |
| 107 |
if main_lg: |
| 108 |
new_locales = [main_locale] |
| 109 |
for locale in locales[1::]: |
| 110 |
if locale.get(lg_key, main_lg) == main_lg: |
| 111 |
new_locales.append(locale) |
| 112 |
locales = new_locales |
| 113 |
for locale in locales: |
| 114 |
try: |
| 115 |
return locale.get_term(name, form, zero_padded=zero_padded) |
| 116 |
except IndexError: # TODO: create custom exception |
| 117 |
continue |
| 118 |
|
| 119 |
def get_plural_term(self, name, *args, **kwargs): |
| 120 |
""" |
| 121 |
Return plural form of the term or empty string if no term found |
| 122 |
""" |
| 123 |
if (term := self.get_term(name, *args, **kwargs)) is not None: |
| 124 |
return term.multiple |
| 125 |
return String('') |
| 126 |
|
| 127 |
def get_single_term(self, name, *args, **kwargs): |
| 128 |
""" |
| 129 |
Return singular form of the term or empty string if no term found |
| 130 |
""" |
| 131 |
if (term := self.get_term(name, *args, **kwargs)) is not None: |
| 132 |
return term.single |
| 133 |
return String('') |
| 134 |
|
| 135 |
def get_date(self, form): |
| 136 |
for locale in self.get_root().locales: |
| 137 |
try: |
| 138 |
return locale.get_date(form) |
| 139 |
except IndexError: |
| 140 |
continue |
| 141 |
|
| 142 |
def get_locale_option(self, name): |
| 143 |
root = self.get_root() |
| 144 |
if not hasattr(root, 'locales') or root.locales is None: |
| 145 |
# root element is Locale, not an iterable of Locales |
| 146 |
return root.get_option(name) |
| 147 |
for locale in root.locales: |
| 148 |
try: |
| 149 |
return locale.get_option(name) |
| 150 |
except IndexError: |
| 151 |
continue |
| 152 |
|
| 153 |
|
| 154 |
# Top level elements |
| 155 |
|
| 156 |
class Style(CitationStylesElement): |
| 157 |
def set_locale_list(self, output_locale, validate=True): |
| 158 |
"""Set up list of locales in which to search for localizable units""" |
| 159 |
from .frontend import CitationStylesLocale |
| 160 |
|
| 161 |
self.locales = [] |
| 162 |
system_locales_added = set() |
| 163 |
|
| 164 |
def add_instyle_locale(locale): |
| 165 |
expr = ('./cs:locale[@xml:lang="{}"]'.format(locale) |
| 166 |
if locale else './cs:locale[not(@xml:lang)]') |
| 167 |
results = self.xpath_search(expr) |
| 168 |
if results: |
| 169 |
locale_element, = results |
| 170 |
self.locales.append(locale_element) |
| 171 |
|
| 172 |
def add_system_locale(locale): |
| 173 |
if locale not in system_locales_added: |
| 174 |
csl_locale = CitationStylesLocale(locale, validate=validate) |
| 175 |
self.locales.append(csl_locale.root) |
| 176 |
system_locales_added.add(locale) |
| 177 |
|
| 178 |
# 1) (in-style locale) chosen dialect |
| 179 |
add_instyle_locale(output_locale) |
| 180 |
# 2) (in-style locale) matching language |
| 181 |
language = output_locale.split('-')[0] |
| 182 |
add_instyle_locale(language) |
| 183 |
# 3) (in-style locale) no language set |
| 184 |
add_instyle_locale(None) |
| 185 |
# 4) (locale files) chosen or primary dialect |
| 186 |
if output_locale in LANGUAGE_NAMES: |
| 187 |
add_system_locale(output_locale) |
| 188 |
# 5) (locale files) fall back to primary language dialect |
| 189 |
if language in PRIMARY_DIALECTS: |
| 190 |
add_system_locale(PRIMARY_DIALECTS[language]) |
| 191 |
# 6) (locale files) default locale (en-US) |
| 192 |
add_system_locale('en-US') |
| 193 |
for locale in self.locales: |
| 194 |
locale.style = self |
| 195 |
|
| 196 |
|
| 197 |
class Locale(CitationStylesElement): |
| 198 |
_default_options = {'limit-day-ordinals-to-day-1': 'false', |
| 199 |
'punctuation-in-quote': 'false'} |
| 200 |
|
| 201 |
def get_term(self, name, form=None, zero_padded=False): |
| 202 |
attributes = "@name='{}'".format(name) |
| 203 |
if form is not None: |
| 204 |
attributes += " and @form='{}'".format(form) |
| 205 |
else: |
| 206 |
attributes += " and not(@form)" |
| 207 |
if zero_padded: |
| 208 |
attributes += "and not(@match='whole-number')" |
| 209 |
attributes += "and not(@match='last-two-digits')" |
| 210 |
expr = './cs:term[{}]'.format(attributes) |
| 211 |
try: |
| 212 |
return self.terms.xpath_search(expr)[0] |
| 213 |
except AttributeError: |
| 214 |
raise IndexError |
| 215 |
|
| 216 |
def get_date(self, form): |
| 217 |
expr = "./cs:date[@form='{}']".format(form) |
| 218 |
return self.xpath_search(expr)[0] |
| 219 |
|
| 220 |
def get_option(self, name): |
| 221 |
options = self.find('cs:style-options', self.nsmap) |
| 222 |
if options is None: |
| 223 |
raise IndexError |
| 224 |
return options.get(name, self._default_options[name]) |
| 225 |
|
| 226 |
def get_formatter(self): |
| 227 |
return self.style.formatter |
| 228 |
|
| 229 |
|
| 230 |
class FormattingInstructions(object): |
| 231 |
def get_option(self, name): |
| 232 |
if name in self._default_options: |
| 233 |
return self.get(name, self._default_options[name]) |
| 234 |
else: |
| 235 |
return self.get(name, self.get_root().get_option(name)) |
| 236 |
|
| 237 |
def render(self, reference): |
| 238 |
raise NotImplementedError |
| 239 |
|
| 240 |
|
| 241 |
class Citation(FormattingInstructions, CitationStylesElement): |
| 242 |
_default_options = {# disambiguation |
| 243 |
'disambiguate-add-names': False, |
| 244 |
'disambiguate-add-givenname': False, |
| 245 |
'givenname-disambiguation-rule': 'all-names', |
| 246 |
'disambiguate-add-year-suffix': False, |
| 247 |
|
| 248 |
# citation collapsing |
| 249 |
'collapse': None, |
| 250 |
'year-suffix-delimiter': None, |
| 251 |
'after-collapse-delimiter': None, |
| 252 |
|
| 253 |
# note distance |
| 254 |
'near-note-distance': 5} |
| 255 |
|
| 256 |
def render(self, citation, cites, callback): |
| 257 |
self.cites = cites |
| 258 |
return self.layout.render_citation(citation, callback) |
| 259 |
|
| 260 |
|
| 261 |
class Bibliography(FormattingInstructions, CitationStylesElement): |
| 262 |
_default_options = {# whitespace |
| 263 |
'hanging-indent': False, |
| 264 |
'second-field-align': None, |
| 265 |
'line-spacing': 1, |
| 266 |
'entry-spacing': 1, |
| 267 |
|
| 268 |
# reference grouping |
| 269 |
'subsequent-author-substitute': None} |
| 270 |
|
| 271 |
def sort(self, citation_items): |
| 272 |
return self.layout.sort_bibliography(citation_items) |
| 273 |
|
| 274 |
def render(self, citation_items): |
| 275 |
return self.layout.render_bibliography(citation_items) |
| 276 |
|
| 277 |
|
| 278 |
# Style behavior |
| 279 |
|
| 280 |
class Formatted(object): |
| 281 |
def format(self, string): |
| 282 |
if isinstance(string, (int, float)): |
| 283 |
string = str(string) |
| 284 |
text = self.font_style(string) |
| 285 |
text = self.font_variant(text) |
| 286 |
text = self.font_weight(text) |
| 287 |
text = self.text_decoration(text) |
| 288 |
text = self.vertical_align(text) |
| 289 |
return text |
| 290 |
|
| 291 |
def font_style(self, text): |
| 292 |
formatter = self.get_formatter() |
| 293 |
font_style = self.get('font-style', 'normal') |
| 294 |
if font_style == 'normal': |
| 295 |
formatted = text |
| 296 |
elif font_style == 'italic': |
| 297 |
formatted = formatter.Italic(text) |
| 298 |
elif font_style == 'oblique': |
| 299 |
formatted = formatter.Oblique(text) |
| 300 |
return formatted |
| 301 |
|
| 302 |
def font_variant(self, text): |
| 303 |
formatter = self.get_formatter() |
| 304 |
font_variant = self.get('font-variant', 'normal') |
| 305 |
if font_variant == 'normal': |
| 306 |
formatted = text |
| 307 |
elif font_variant == 'small-caps': |
| 308 |
formatted = formatter.SmallCaps(text) |
| 309 |
return formatted |
| 310 |
|
| 311 |
def font_weight(self, text): |
| 312 |
formatter = self.get_formatter() |
| 313 |
font_weight = self.get('font-weight', 'normal') |
| 314 |
if font_weight == 'normal': |
| 315 |
formatted = text |
| 316 |
elif font_weight == 'bold': |
| 317 |
formatted = formatter.Bold(text) |
| 318 |
elif font_weight == 'light': |
| 319 |
formatted = formatter.Light(text) |
| 320 |
return formatted |
| 321 |
|
| 322 |
def text_decoration(self, text): |
| 323 |
formatter = self.get_formatter() |
| 324 |
text_decoration = self.get('text-decoration', 'none') |
| 325 |
if text_decoration == 'none': |
| 326 |
formatted = text |
| 327 |
elif text_decoration == 'underline': |
| 328 |
formatted = formatter.Underline(text) |
| 329 |
return formatted |
| 330 |
|
| 331 |
def vertical_align(self, text): |
| 332 |
formatter = self.get_formatter() |
| 333 |
vertical_align = self.get('vertical-align', 'baseline') |
| 334 |
if vertical_align == 'baseline': |
| 335 |
formatted = text |
| 336 |
elif vertical_align == 'sup': |
| 337 |
formatted = formatter.Superscript(text) |
| 338 |
elif vertical_align == 'sub': |
| 339 |
formatted = formatter.Subscript(text) |
| 340 |
return formatted |
| 341 |
|
| 342 |
|
| 343 |
class Affixed(object): |
| 344 |
def wrap(self, string): |
| 345 |
if string is not None: |
| 346 |
prefix = self.get('prefix', '') |
| 347 |
suffix = self.get('suffix', '') |
| 348 |
string = normalize_seam(prefix, string) |
| 349 |
text = prefix + string |
| 350 |
return text + normalize_seam(text, suffix) |
| 351 |
return None |
| 352 |
|
| 353 |
|
| 354 |
class Delimited(object): |
| 355 |
def join(self, strings, default_delimiter=''): |
| 356 |
delimiter = self.get('delimiter', default_delimiter) |
| 357 |
try: |
| 358 |
text = join((s for s in strings if s is not None), delimiter) |
| 359 |
except: |
| 360 |
text = String('') |
| 361 |
return text |
| 362 |
|
| 363 |
|
| 364 |
class Displayed(object): |
| 365 |
pass |
| 366 |
|
| 367 |
|
| 368 |
class Quoted(object): |
| 369 |
def quote(self, string): |
| 370 |
piq = self.get_locale_option('punctuation-in-quote').lower() == 'true' |
| 371 |
if self.get('quotes', 'false').lower() == 'true': |
| 372 |
open_quote = self.get_single_term(name='open-quote') |
| 373 |
close_quote = self.get_single_term(name='close-quote') |
| 374 |
string = open_quote + string + close_quote |
| 375 |
## quoted_string = QuotedString(string, open_quote, close_quote, piq) |
| 376 |
return string |
| 377 |
|
| 378 |
|
| 379 |
class StrippedPeriods(object): |
| 380 |
def strip_periods(self, string): |
| 381 |
strip_periods = self.get('strip-periods', 'false').lower() == 'true' |
| 382 |
if strip_periods: |
| 383 |
string = string.replace('.', '') |
| 384 |
return string |
| 385 |
|
| 386 |
|
| 387 |
class TextCased(object): |
| 388 |
_stop_words = ['a', 'an', 'and', 'as', 'at', 'but', 'by', 'down', 'for', |
| 389 |
'from', 'in', 'into', 'nor', 'of', 'on', 'onto', 'or', |
| 390 |
'over', 'so', 'the', 'till', 'to', 'up', 'via', 'with', |
| 391 |
'yet'] |
| 392 |
|
| 393 |
def case(self, text, language=None): |
| 394 |
text_case = self.get('text-case') |
| 395 |
if text_case is not None: |
| 396 |
if language != 'en' and text_case == 'title': |
| 397 |
return text |
| 398 |
if text_case == 'lowercase': |
| 399 |
text = text.lower() |
| 400 |
elif text_case == 'uppercase': |
| 401 |
text = text.upper() |
| 402 |
elif text_case == 'capitalize-first': |
| 403 |
text = text.capitalize_first() |
| 404 |
elif text_case == 'capitalize-all': |
| 405 |
output = [] |
| 406 |
for word in text.words(): |
| 407 |
word = word.capitalize_first() |
| 408 |
output.append(word) |
| 409 |
text = ' '.join(output) |
| 410 |
elif text_case == 'title': |
| 411 |
output = [] |
| 412 |
prev = ':' #This ensures first word is capitilized |
| 413 |
for word in text.words(): |
| 414 |
if word.islower() and (str(word) not in self._stop_words or |
| 415 |
prev in (':', '.')): |
| 416 |
word = word.capitalize_first() |
| 417 |
elif word.islower(): #Lowercase stop words |
| 418 |
word = word.soft_lower() |
| 419 |
prev = word[-1] |
| 420 |
output.append(word) |
| 421 |
text = ' '.join(output) |
| 422 |
elif text_case == 'sentence': |
| 423 |
output = [] |
| 424 |
for i, word in enumerate(text.words()): |
| 425 |
if not text.isupper() and not word.isupper(): |
| 426 |
word = word.soft_lower() |
| 427 |
if i == 0: |
| 428 |
word = word.capitalize_first() |
| 429 |
output.append(word) |
| 430 |
text = ' '.join(output) |
| 431 |
return text |
| 432 |
|
| 433 |
|
| 434 |
# Locale elements |
| 435 |
|
| 436 |
class Term(CitationStylesElement): |
| 437 |
@property |
| 438 |
def single(self): |
| 439 |
try: |
| 440 |
text = self.find('cs:single', self.nsmap).text |
| 441 |
except AttributeError: |
| 442 |
text = self.text |
| 443 |
text = self.preformat(text or '') |
| 444 |
return String(text) |
| 445 |
|
| 446 |
@property |
| 447 |
def multiple(self): |
| 448 |
try: |
| 449 |
text = self.find('cs:multiple', self.nsmap).text |
| 450 |
except AttributeError: |
| 451 |
text = self.text |
| 452 |
text = self.preformat(text or '') |
| 453 |
return String(text) |
| 454 |
|
| 455 |
|
| 456 |
# Sorting elements |
| 457 |
|
| 458 |
class Sort(CitationStylesElement): |
| 459 |
def sort(self, items, context): |
| 460 |
# custom sort function to push items with None keys to bottom |
| 461 |
def multi_key_sort(items, keys, descending): |
| 462 |
lst = zip(items, *keys) |
| 463 |
comparers = [(itemgetter(i + 1), descending[i]) |
| 464 |
for i in range(len(keys))] |
| 465 |
def mycmp(left, right): |
| 466 |
for getter, desc in comparers: |
| 467 |
left_key, right_key = getter(left), getter(right) |
| 468 |
if left_key is not None and right_key is not None: |
| 469 |
try: |
| 470 |
left_key = str(left_key.lower()) |
| 471 |
right_key = str(right_key.lower()) |
| 472 |
except AttributeError: |
| 473 |
pass |
| 474 |
try: |
| 475 |
left_key, right_key = (int(str(left_key)), |
| 476 |
int(str(right_key))) |
| 477 |
except ValueError: |
| 478 |
pass |
| 479 |
result = (left_key > right_key) - (left_key < right_key) |
| 480 |
if result: |
| 481 |
return -1 * result if desc else result |
| 482 |
elif left_key is not None: |
| 483 |
return -1 |
| 484 |
elif right_key is not None: |
| 485 |
return 1 |
| 486 |
else: |
| 487 |
continue |
| 488 |
else: |
| 489 |
return 0 |
| 490 |
|
| 491 |
sorted_lst = sorted(lst, key=cmp_to_key(mycmp)) |
| 492 |
return [item[0] for item in sorted_lst] |
| 493 |
|
| 494 |
sort_descending = [] |
| 495 |
sort_keys = [] |
| 496 |
for key in self.findall('cs:key', self.nsmap): |
| 497 |
descending = key.get('sort', 'ascending').lower() == 'descending' |
| 498 |
sort_descending.append(descending) |
| 499 |
sort_keys.append(key.sort_keys(items, context)) |
| 500 |
|
| 501 |
return multi_key_sort(items, sort_keys, sort_descending) |
| 502 |
|
| 503 |
|
| 504 |
class Key(CitationStylesElement): |
| 505 |
def sort_keys(self, items, context): |
| 506 |
if 'variable' in self.attrib: |
| 507 |
variable = self.get('variable').replace('-', '_') |
| 508 |
if variable in NAMES: |
| 509 |
sort_keys = [self._format_name(item, variable) |
| 510 |
for item in items] |
| 511 |
elif variable in DATES: |
| 512 |
sort_keys = [] |
| 513 |
for item in items: |
| 514 |
date = item.reference.get(variable) |
| 515 |
if date is not None: |
| 516 |
sort_keys.append(date.sort_key()) |
| 517 |
else: |
| 518 |
sort_keys.append(None) |
| 519 |
elif variable in NUMBERS: |
| 520 |
sort_keys = [self._format_number(item, variable) |
| 521 |
for item in items] |
| 522 |
elif variable == 'citation_number': |
| 523 |
sort_keys = [item.number for item in items] |
| 524 |
else: |
| 525 |
sort_keys = [item.get_field(variable) for item in items] |
| 526 |
elif 'macro' in self.attrib: |
| 527 |
layout = context.get_layout() |
| 528 |
# override name options |
| 529 |
sort_options = {'name-as-sort-order': 'all'} |
| 530 |
for option in ('names-min', 'names-use-first', 'names-use-last'): |
| 531 |
if option in self.attrib: |
| 532 |
name = option.replace('names', 'et-al') |
| 533 |
sort_options[name] = self.get(option) |
| 534 |
macro = self.get_macro(self.get('macro')) |
| 535 |
sort_keys = [] |
| 536 |
for item in items: |
| 537 |
layout.repressed = {} |
| 538 |
sort_key = macro.render(item, context=context, |
| 539 |
sort_options=sort_options) |
| 540 |
sort_keys.append(sort_key) |
| 541 |
|
| 542 |
return sort_keys |
| 543 |
|
| 544 |
def _format_name(self, item, variable): |
| 545 |
names = item.reference.get(variable) |
| 546 |
if names is not None: |
| 547 |
output = [] |
| 548 |
for name in names: |
| 549 |
demote_ndp = self.get_root().get('demote-non-dropping-particle', |
| 550 |
'display-and-sort').lower() |
| 551 |
sort_separator = self._default_options['sort-separator'] |
| 552 |
|
| 553 |
# TODO: encapsulate in function (to share with Name) |
| 554 |
given, family, dp, ndp, suffix = name.parts() |
| 555 |
if demote_ndp in ('sort-only', 'display-and-sort'): |
| 556 |
given = ' '.join([n for n in (given, dp, ndp) if n]) |
| 557 |
else: |
| 558 |
family = ' '.join([n for n in (ndp, family) if n]) |
| 559 |
given = ' '.join([n for n in (given, dp) if n]) |
| 560 |
|
| 561 |
order = family, given, suffix |
| 562 |
output.append(sort_separator.join([n for n in order if n])) |
| 563 |
return ';'.join(output) |
| 564 |
else: |
| 565 |
return None |
| 566 |
|
| 567 |
def _format_number(self, item, variable): |
| 568 |
date = item.reference.get(variable) |
| 569 |
if date is not None: |
| 570 |
try: |
| 571 |
return str(Number.re_numeric.match(date).group(1)) |
| 572 |
except AttributeError: |
| 573 |
return date |
| 574 |
else: |
| 575 |
return None |
| 576 |
|
| 577 |
|
| 578 |
# Rendering elements |
| 579 |
|
| 580 |
class Parent(object): |
| 581 |
def calls_variable(self): |
| 582 |
return any([child.calls_variable() for child in self.getchildren()]) |
| 583 |
|
| 584 |
def process_children(self, item, **kwargs): |
| 585 |
output = [] |
| 586 |
for child in self.iterchildren(): |
| 587 |
try: |
| 588 |
text = child.process(item, **kwargs) |
| 589 |
if text is not None: |
| 590 |
output.append(text) |
| 591 |
except VariableError: |
| 592 |
pass |
| 593 |
if output: |
| 594 |
return ''.join(output) |
| 595 |
else: |
| 596 |
return None |
| 597 |
|
| 598 |
def render_children(self, item, delimiter='', **kwargs): |
| 599 |
# `delimiter` is the delimiter inherited from an enclosing element (a |
| 600 |
# `cs:group`). `cs:choose` is transparent, so this delimiter has to be |
| 601 |
# threaded through `cs:if`/`cs:else-if`/`cs:else` to delimit their |
| 602 |
# rendered children (and any nested `cs:choose`). |
| 603 |
output = [] |
| 604 |
for child in self.iterchildren(): |
| 605 |
try: |
| 606 |
if isinstance(child, Choose): |
| 607 |
text = child.render(item, delimiter=delimiter, **kwargs) |
| 608 |
else: |
| 609 |
text = child.render(item, **kwargs) |
| 610 |
if text is not None: |
| 611 |
output.append(text) |
| 612 |
except VariableError: |
| 613 |
pass |
| 614 |
if output: |
| 615 |
return join(output, delimiter) |
| 616 |
else: |
| 617 |
return None |
| 618 |
|
| 619 |
|
| 620 |
class Macro(CitationStylesElement, Parent): |
| 621 |
def process(self, item, context=None, sort_options=None): |
| 622 |
return self.process_children(item, context=context, |
| 623 |
sort_options=sort_options) |
| 624 |
|
| 625 |
def render(self, item, context=None, sort_options=None): |
| 626 |
return self.render_children(item, context=context, |
| 627 |
sort_options=sort_options) |
| 628 |
|
| 629 |
|
| 630 |
class Layout(CitationStylesElement, Parent, Formatted, Affixed, Delimited): |
| 631 |
def render_citation(self, citation, callback): |
| 632 |
# first sort citation items according to bibliography order |
| 633 |
bibliography = citation.bibliography |
| 634 |
good_cites = [cite for cite in citation.cites if not cite.is_bad()] |
| 635 |
bad_cites = [cite for cite in citation.cites if cite.is_bad()] |
| 636 |
good_cites.sort(key=lambda item: bibliography.keys.index(item.key)) |
| 637 |
# sort using citation/sort element |
| 638 |
if self.getparent().sort is not None: |
| 639 |
good_cites = self.getparent().sort.sort(good_cites, self) |
| 640 |
out = [] |
| 641 |
for item in good_cites: |
| 642 |
self.repressed = {} |
| 643 |
prefix = item.get('prefix', '') |
| 644 |
suffix = item.get('suffix', '') |
| 645 |
try: |
| 646 |
output = self.render_children(item) |
| 647 |
if output is not None: |
| 648 |
text = prefix + output + suffix |
| 649 |
out.append(text) |
| 650 |
self.getparent().cites.append(item) |
| 651 |
except VariableError: |
| 652 |
pass |
| 653 |
for item in bad_cites: |
| 654 |
callback_value = callback(item) |
| 655 |
out.append(callback_value or '{}?'.format(item.key)) |
| 656 |
return self.format(self.wrap(self.join(out))) |
| 657 |
|
| 658 |
def sort_bibliography(self, citation_items): |
| 659 |
sort = self.getparent().find('cs:sort', self.nsmap) |
| 660 |
if sort is not None: |
| 661 |
citation_items = sort.sort(citation_items, self) |
| 662 |
return citation_items |
| 663 |
|
| 664 |
def render_bibliography(self, citation_items): |
| 665 |
output_items = [] |
| 666 |
for item in citation_items: |
| 667 |
self.repressed = {} |
| 668 |
text = self.format(self.wrap(self.render_children(item))) |
| 669 |
if text is not None: |
| 670 |
output_items.append(text) |
| 671 |
return output_items |
| 672 |
|
| 673 |
|
| 674 |
class FormatNumber(object): |
| 675 |
def _process(self, value, variable): |
| 676 |
page_range_delimiter = self.get_single_term(name='page-range-delimiter') \ |
| 677 |
if variable.startswith('page') else None |
| 678 |
range_delimiter = (page_range_delimiter |
| 679 |
or self.unicode_character('EN DASH')) |
| 680 |
|
| 681 |
en_dash = unicodedata.lookup('EN DASH') |
| 682 |
def format_number_or_range(item): |
| 683 |
try: |
| 684 |
first, last = (number.strip() for number |
| 685 |
in item.replace(en_dash, '-').split('-')) |
| 686 |
except ValueError: |
| 687 |
return self.format_number(item.strip()) |
| 688 |
first = self.format_number(first) |
| 689 |
if variable == 'page-first': |
| 690 |
return first |
| 691 |
last = self.format_number(self._format_last_page(first, last) |
| 692 |
if variable == 'page' else last) |
| 693 |
return join((first, last), range_delimiter) |
| 694 |
|
| 695 |
amp_delimiter = ' ' + self.unicode_character('AMPERSAND') + ' ' |
| 696 |
return join((join((format_number_or_range(item) |
| 697 |
for item in comma_item.split('&')), amp_delimiter) |
| 698 |
for comma_item in str(value).split(',')), delimiter=', ') |
| 699 |
|
| 700 |
def _format_last_page(self, first, last): |
| 701 |
def find_common(first, last): |
| 702 |
count = 0 |
| 703 |
for count, (f, l) in enumerate(zip(first, last)): |
| 704 |
if f != l: |
| 705 |
return count |
| 706 |
return count + 1 |
| 707 |
|
| 708 |
range_format = self.get_root().get_option('page-range-format') |
| 709 |
common = find_common(first, last) |
| 710 |
if range_format in ('chicago', 'chicago-15', 'chicago-16'): |
| 711 |
m = re.search(r'\d+', first) |
| 712 |
if not m: |
| 713 |
return last |
| 714 |
first_number = int(m.group()) |
| 715 |
if first_number < 100 or first_number % 100 == 0: |
| 716 |
range_format = 'expanded' |
| 717 |
elif len(first) >= 4 and common < 2: |
| 718 |
range_format = 'expanded' |
| 719 |
elif first_number % 100 in range(1, 10): |
| 720 |
range_format = 'minimal' |
| 721 |
elif first_number % 100 in range(10, 100): |
| 722 |
range_format = 'minimal-two' |
| 723 |
index = 0 # 'expanded' format (and default): return the full last page |
| 724 |
if range_format == 'minimal': |
| 725 |
index = common |
| 726 |
elif range_format == 'minimal-two': |
| 727 |
index = min(common, len(first) - 2) |
| 728 |
return last[index:] |
| 729 |
|
| 730 |
def format_number(self, number): |
| 731 |
return str(number) |
| 732 |
|
| 733 |
|
| 734 |
class Text(CitationStylesElement, FormatNumber, Formatted, Affixed, Quoted, |
| 735 |
TextCased, StrippedPeriods): |
| 736 |
generated_variables = ('year-suffix',) |
| 737 |
|
| 738 |
def calls_variable(self): |
| 739 |
if 'variable' in self.attrib: |
| 740 |
return self.get('variable') not in self.generated_variables |
| 741 |
elif 'macro' in self.attrib: |
| 742 |
return self.get_macro(self.get('macro')).calls_variable() |
| 743 |
else: |
| 744 |
return False |
| 745 |
|
| 746 |
def render(self, *args, **kwargs): |
| 747 |
text, language = self.process(*args, **kwargs) |
| 748 |
return self.markup(text, language) |
| 749 |
|
| 750 |
def process(self, item, context=None, **kwargs): |
| 751 |
if context is None: |
| 752 |
context = self |
| 753 |
|
| 754 |
try: |
| 755 |
language = item.reference.language[:2] |
| 756 |
except VariableError: |
| 757 |
language = self.get_root().get('default-locale', 'en')[:2] |
| 758 |
if 'variable' in self.attrib: |
| 759 |
text = self._variable(item, context) |
| 760 |
elif 'macro' in self.attrib: |
| 761 |
text = self.get_macro(self.get('macro')).render(item, context) |
| 762 |
elif 'term' in self.attrib: |
| 763 |
text = self._term(item) |
| 764 |
elif 'value' in self.attrib: |
| 765 |
text = String(self.preformat(self.get('value'))) |
| 766 |
|
| 767 |
return text, language |
| 768 |
|
| 769 |
def _variable(self, item, context): |
| 770 |
variable = self.get('variable') |
| 771 |
repressed = context.get_layout().repressed |
| 772 |
if self.tag in repressed and variable in repressed[self.tag]: |
| 773 |
return None |
| 774 |
|
| 775 |
if self.get('form') == 'short': |
| 776 |
short_variable = variable + '-short' |
| 777 |
if short_variable.replace('-', '_') in item.reference: |
| 778 |
variable = short_variable |
| 779 |
|
| 780 |
if variable.startswith('page'): |
| 781 |
text = self._process(item.reference.page, variable) |
| 782 |
elif variable == 'citation-number': |
| 783 |
text = item.number |
| 784 |
elif variable == 'locator': |
| 785 |
en_dash = self.unicode_character('EN DASH') |
| 786 |
text = str(item.locator.identifier).replace('-', en_dash) |
| 787 |
else: |
| 788 |
text = item.reference[variable.replace('-', '_')] |
| 789 |
|
| 790 |
return text |
| 791 |
|
| 792 |
def _term(self, item): |
| 793 |
form = self.get('form', 'long') |
| 794 |
plural = self.get('plural', 'false').lower() == 'true' |
| 795 |
variable = self.get('term') |
| 796 |
if plural: |
| 797 |
text = self.get_plural_term(name=variable, |
| 798 |
form=form if form != 'long' else None) |
| 799 |
else: |
| 800 |
text = self.get_single_term(name=variable, |
| 801 |
form=form if form != 'long' else None) |
| 802 |
|
| 803 |
return text |
| 804 |
|
| 805 |
def markup(self, text, language): |
| 806 |
if text: |
| 807 |
tmp = self.format(self.case(self.strip_periods(text), language)) |
| 808 |
return self.wrap(self.quote(tmp)) |
| 809 |
else: |
| 810 |
return None |
| 811 |
|
| 812 |
|
| 813 |
class Date(CitationStylesElement, Parent, Formatted, Affixed, Delimited): |
| 814 |
def calls_variable(self): |
| 815 |
return True |
| 816 |
|
| 817 |
def is_locale_date(self): |
| 818 |
expr = './ancestor::cs:locale[1]' |
| 819 |
try: |
| 820 |
self.xpath_search(expr)[0] |
| 821 |
return True |
| 822 |
except IndexError: |
| 823 |
return False |
| 824 |
|
| 825 |
def render_single_date(self, date, show_parts=None, context=None): |
| 826 |
form = self.get('form') |
| 827 |
if context != self: |
| 828 |
parts = self.parts(date, show_parts, context) |
| 829 |
else: |
| 830 |
parts = self.parts(date, show_parts) |
| 831 |
if parts: |
| 832 |
style_context = context if self.is_locale_date() else self |
| 833 |
return style_context.join(parts) |
| 834 |
else: |
| 835 |
return None |
| 836 |
|
| 837 |
def render_date_range(self, date_range, show_parts=None, context=None): |
| 838 |
same_show_parts = [] |
| 839 |
if date_range.end.is_nil(): |
| 840 |
same = None |
| 841 |
diff_begin = self.render_single_date(date_range.begin, show_parts, |
| 842 |
context) |
| 843 |
diff_end = '' |
| 844 |
else: |
| 845 |
if date_range.begin.year == date_range.end.year: |
| 846 |
show_parts.remove('year') |
| 847 |
same_show_parts.append('year') |
| 848 |
try: |
| 849 |
if ('month' in show_parts and |
| 850 |
date_range.begin.month == date_range.end.month): |
| 851 |
show_parts.remove('month') |
| 852 |
same_show_parts.append('month') |
| 853 |
try: |
| 854 |
if ('day' in show_parts and |
| 855 |
date_range.begin.day == date_range.end.day): |
| 856 |
show_parts.remove('day') |
| 857 |
same_show_parts.append('day') |
| 858 |
except AttributeError: |
| 859 |
show_parts.remove('day') |
| 860 |
except AttributeError: |
| 861 |
show_parts.remove('month') |
| 862 |
|
| 863 |
same = self.render_single_date(date_range.end, same_show_parts, |
| 864 |
context) |
| 865 |
diff_begin = self.render_single_date(date_range.begin, show_parts, |
| 866 |
context) |
| 867 |
diff_end = self.render_single_date(date_range.end, show_parts, |
| 868 |
context) |
| 869 |
|
| 870 |
if not (diff_begin and diff_begin): |
| 871 |
return None |
| 872 |
|
| 873 |
diff = (diff_begin.rstrip() + self.unicode_character('EN DASH') + |
| 874 |
diff_end) |
| 875 |
if same: |
| 876 |
text = context.join([diff, same.rstrip()]) |
| 877 |
else: |
| 878 |
text = diff |
| 879 |
|
| 880 |
return text |
| 881 |
|
| 882 |
def process(self, item, variable=None, show_parts=None, context=None, |
| 883 |
**kwargs): |
| 884 |
if variable is None: |
| 885 |
variable = self.get('variable') |
| 886 |
if show_parts is None: |
| 887 |
show_parts = ['year', 'month', 'day'] |
| 888 |
if context is None: |
| 889 |
context = self |
| 890 |
|
| 891 |
form = self.get('form') |
| 892 |
date_parts = self.get('date-parts') |
| 893 |
if not self.is_locale_date() and form is not None: |
| 894 |
localized_date = self.get_date(form) |
| 895 |
if date_parts is not None: |
| 896 |
show_parts = date_parts.split('-') |
| 897 |
return localized_date.render(item, variable, |
| 898 |
show_parts=show_parts, context=self) |
| 899 |
else: |
| 900 |
date_or_range = item.reference[variable.replace('-', '_')] |
| 901 |
if not date_or_range: |
| 902 |
text = None |
| 903 |
elif isinstance(date_or_range, LiteralDate): |
| 904 |
text = date_or_range.text |
| 905 |
elif isinstance(date_or_range, DateRange): |
| 906 |
text = self.render_date_range(date_or_range, show_parts, |
| 907 |
context) |
| 908 |
else: |
| 909 |
text = self.render_single_date(date_or_range, show_parts, |
| 910 |
context) |
| 911 |
if text is not None: |
| 912 |
style_context = context if self.is_locale_date() else self |
| 913 |
return style_context.wrap(text) |
| 914 |
else: |
| 915 |
return None |
| 916 |
|
| 917 |
def parts(self, date, show_parts, context=None): |
| 918 |
output = [] |
| 919 |
for part in self.iterchildren(): |
| 920 |
if part.get('name') in show_parts: |
| 921 |
try: |
| 922 |
part_text = part.render(date, context) |
| 923 |
if part_text is not None: |
| 924 |
output.append(part_text) |
| 925 |
except VariableError: |
| 926 |
pass |
| 927 |
return output |
| 928 |
|
| 929 |
def markup(self, text): |
| 930 |
# TODO: fix |
| 931 |
return text |
| 932 |
|
| 933 |
|
| 934 |
class Date_Part(CitationStylesElement, Formatted, Affixed, TextCased, |
| 935 |
StrippedPeriods): |
| 936 |
def process(self, date, context=None): |
| 937 |
name = self.get('name') |
| 938 |
range_delimiter = self.get('range-delimiter', '-') |
| 939 |
attrib = self.attrib |
| 940 |
|
| 941 |
if context is None: |
| 942 |
context = self |
| 943 |
try: |
| 944 |
expr = './cs:date-part[@name="{}"]'.format(name) |
| 945 |
attrib.update(dict(context.xpath_search(expr)[0].attrib)) |
| 946 |
except (AttributeError, IndexError): |
| 947 |
pass |
| 948 |
|
| 949 |
if name == 'day': |
| 950 |
form = self.get('form', 'numeric') |
| 951 |
if (form == 'ordinal' |
| 952 |
and self.get_locale_option('limit-day-ordinals-to-day-1') |
| 953 |
.lower() == 'true' |
| 954 |
and date.day > 1): |
| 955 |
form = 'numeric' |
| 956 |
|
| 957 |
if form == 'numeric': |
| 958 |
text = date.day |
| 959 |
elif form == 'numeric-leading-zeros': |
| 960 |
text = '{:02}'.format(date.day) |
| 961 |
elif form == 'ordinal': |
| 962 |
text = to_ordinal(date.day, context) |
| 963 |
elif name == 'month': |
| 964 |
form = self.get('form', 'long') |
| 965 |
strip_periods = self.get('form', False) |
| 966 |
try: |
| 967 |
index = date.month |
| 968 |
term = 'month' |
| 969 |
except VariableError: |
| 970 |
index = date.season |
| 971 |
term = 'season' |
| 972 |
|
| 973 |
if form == 'long' or form == 'short': |
| 974 |
text = context.get_single_term(name='{}-{:02}'.format(term, index), |
| 975 |
form='short' if form == 'short' else None) |
| 976 |
else: |
| 977 |
assert term == 'month' |
| 978 |
if form == 'numeric': |
| 979 |
text = '{}'.format(index) |
| 980 |
elif form == 'numeric-leading-zeros': |
| 981 |
text = '{:02}'.format(index) |
| 982 |
elif name == 'year': |
| 983 |
form = self.get('form', 'long') |
| 984 |
if form == 'long': |
| 985 |
text = str(abs(date.year)) |
| 986 |
if date.year < 0: |
| 987 |
text += context.get_single_term(name='bc') |
| 988 |
elif date.year < 1000: |
| 989 |
text += context.get_single_term(name='ad') |
| 990 |
elif form == 'short': |
| 991 |
text = str(date.year)[-2:] |
| 992 |
|
| 993 |
return text |
| 994 |
|
| 995 |
def markup(self, text): |
| 996 |
if text: |
| 997 |
return self.wrap(self.format(self.case(self.strip_periods(text)))) |
| 998 |
else: |
| 999 |
return None |
| 1000 |
|
| 1001 |
|
| 1002 |
class Number(CitationStylesElement, FormatNumber, Formatted, Affixed, Displayed, |
| 1003 |
TextCased, StrippedPeriods): |
| 1004 |
def calls_variable(self): |
| 1005 |
return True |
| 1006 |
|
| 1007 |
def process(self, item, context=None, **kwargs): |
| 1008 |
variable = self.get('variable') |
| 1009 |
if variable == 'locator': |
| 1010 |
try: |
| 1011 |
variable = item.locator.label |
| 1012 |
value = item.locator.identifier |
| 1013 |
except KeyError: |
| 1014 |
return None |
| 1015 |
elif variable == 'page-first': |
| 1016 |
value = item.reference.page |
| 1017 |
else: |
| 1018 |
value = item.reference[variable] |
| 1019 |
return self._process(value, variable) |
| 1020 |
|
| 1021 |
def format_number(self, number): |
| 1022 |
form = self.get('form', 'numeric') |
| 1023 |
try: |
| 1024 |
number = int(number) |
| 1025 |
except ValueError: |
| 1026 |
return number |
| 1027 |
if form == 'numeric': |
| 1028 |
text = str(number) |
| 1029 |
elif form == 'ordinal' or form == 'long-ordinal' and number > 10: |
| 1030 |
text = to_ordinal(number, self) |
| 1031 |
elif form == 'long-ordinal': |
| 1032 |
text = self.get_single_term(name='long-ordinal-{:02}'.format(number)) |
| 1033 |
elif form == 'roman': |
| 1034 |
text = romanize(number).lower() |
| 1035 |
return text |
| 1036 |
|
| 1037 |
def markup(self, text): |
| 1038 |
if text: |
| 1039 |
return self.wrap(self.format(self.case(self.strip_periods(text)))) |
| 1040 |
else: |
| 1041 |
return None |
| 1042 |
|
| 1043 |
|
| 1044 |
class Names(CitationStylesElement, Parent, Formatted, Affixed, Delimited): |
| 1045 |
def calls_variable(self): |
| 1046 |
return True |
| 1047 |
|
| 1048 |
def get_parent_delimiter(self, context=None): |
| 1049 |
expr = './ancestor::*[self::cs:citation or self::cs:bibliography][1]' |
| 1050 |
if context is None: |
| 1051 |
context = self |
| 1052 |
parent = context.xpath_search(expr)[0] |
| 1053 |
return parent.get_option('names-delimiter') |
| 1054 |
|
| 1055 |
def substitute(self): |
| 1056 |
expr = './cs:substitute[1]' |
| 1057 |
try: |
| 1058 |
result = self.xpath_search(expr)[0] |
| 1059 |
except IndexError: |
| 1060 |
result = None |
| 1061 |
return result |
| 1062 |
|
| 1063 |
def process(self, item, names_context=None, context=None, **kwargs): |
| 1064 |
if context is None: |
| 1065 |
context = self |
| 1066 |
if names_context is None: |
| 1067 |
names_context = self |
| 1068 |
|
| 1069 |
roles = self.get('variable').split() |
| 1070 |
try: |
| 1071 |
ed_trans = (set(roles) == set(['editor', 'translator']) and |
| 1072 |
item.reference.editor == item.reference.translator and |
| 1073 |
self.get_term('editortranslator').getchildren()) |
| 1074 |
if ed_trans: |
| 1075 |
roles = ['editor'] |
| 1076 |
except VariableError: |
| 1077 |
ed_trans = False |
| 1078 |
|
| 1079 |
output = [] |
| 1080 |
for role in roles: |
| 1081 |
if role in item.reference: |
| 1082 |
name_elem = names_context.name |
| 1083 |
if name_elem is None: |
| 1084 |
name_elem = Name() |
| 1085 |
names_context.insert(0, name_elem) |
| 1086 |
text = name_elem.render(item, role, context=context, **kwargs) |
| 1087 |
plural = len(item.reference[role]) > 1 |
| 1088 |
try: |
| 1089 |
if ed_trans: |
| 1090 |
role = 'editortranslator' |
| 1091 |
label_element = names_context.label |
| 1092 |
label = label_element.render(item, role, plural, **kwargs) |
| 1093 |
if label is not None: |
| 1094 |
if label_element is names_context.getchildren()[0]: |
| 1095 |
text = label + text |
| 1096 |
else: |
| 1097 |
text = text + label |
| 1098 |
except AttributeError: |
| 1099 |
pass |
| 1100 |
output.append(text) |
| 1101 |
|
| 1102 |
if output: |
| 1103 |
try: |
| 1104 |
total = sum(output) |
| 1105 |
except TypeError: |
| 1106 |
is_int = False |
| 1107 |
else: |
| 1108 |
is_int = isinstance(total, int) |
| 1109 |
if is_int: |
| 1110 |
text = str(total) if total > 0 else None |
| 1111 |
else: |
| 1112 |
text = self.join(output, self.get_parent_delimiter(context)) |
| 1113 |
else: |
| 1114 |
substitute = self.substitute() |
| 1115 |
if substitute is not None: |
| 1116 |
text = substitute.render(item, context=context, **kwargs) |
| 1117 |
|
| 1118 |
try: |
| 1119 |
return text |
| 1120 |
except NameError: |
| 1121 |
raise VariableError |
| 1122 |
|
| 1123 |
def markup(self, text): |
| 1124 |
if text: |
| 1125 |
return self.wrap(self.format(text)) |
| 1126 |
else: |
| 1127 |
return None |
| 1128 |
|
| 1129 |
|
| 1130 |
class Name(CitationStylesElement, Formatted, Affixed, Delimited): |
| 1131 |
def get_option(self, name, context=None, sort_options=None): |
| 1132 |
try: |
| 1133 |
value = sort_options[name] |
| 1134 |
except (TypeError, KeyError): |
| 1135 |
expr = ('./ancestor::*[self::cs:citation or ' |
| 1136 |
'self::cs:bibliography][1]') |
| 1137 |
if context is None: |
| 1138 |
context = self |
| 1139 |
parent = context.xpath_search(expr)[0] |
| 1140 |
if name in ('form', 'delimiter'): |
| 1141 |
value = self.get(name, parent.get_option('name-' + name)) |
| 1142 |
else: |
| 1143 |
value = self.get(name, parent.get_option(name)) |
| 1144 |
|
| 1145 |
if name in ('initialize-with-hyphen', 'et-al-use-last'): |
| 1146 |
value = value.lower() == 'true' |
| 1147 |
elif name.startswith('et-al'): |
| 1148 |
value = int(value) |
| 1149 |
|
| 1150 |
return value |
| 1151 |
|
| 1152 |
def et_al(self): |
| 1153 |
expr = './following-sibling::cs:et-al[1]' |
| 1154 |
try: |
| 1155 |
result = self.xpath_search(expr)[0].render() |
| 1156 |
except IndexError: |
| 1157 |
result = self.get_single_term(name='et-al') |
| 1158 |
return result |
| 1159 |
|
| 1160 |
def process(self, item, variable, context=None, sort_options=None, **kwargs): |
| 1161 |
def get_option(name): |
| 1162 |
return self.get_option(name, context, sort_options) |
| 1163 |
|
| 1164 |
and_ = get_option('and') |
| 1165 |
delimiter = get_option('delimiter') |
| 1166 |
delimiter_precedes_et_al = get_option('delimiter-precedes-et-al') |
| 1167 |
delimiter_precedes_last = get_option('delimiter-precedes-last') |
| 1168 |
|
| 1169 |
et_al_min = get_option('et-al-min') |
| 1170 |
et_al_use_first = get_option('et-al-use-first') |
| 1171 |
et_al_subseq_min = get_option('et-al-subsequent-min') |
| 1172 |
et_al_subseq_use_first = get_option('et-al-subsequent-use-first') |
| 1173 |
et_al_use_last = get_option('et-al-use-last') |
| 1174 |
|
| 1175 |
initialize_with = get_option('initialize-with') |
| 1176 |
name_as_sort_order = get_option('name-as-sort-order') |
| 1177 |
sort_separator = get_option('sort-separator') |
| 1178 |
|
| 1179 |
form = get_option('form') |
| 1180 |
demote_ndp = get_option('demote-non-dropping-particle') |
| 1181 |
|
| 1182 |
def format_name_parts(given, family): |
| 1183 |
for part in self.findall('cs:name-part', self.nsmap): |
| 1184 |
given, family = part.format_part(given, family) |
| 1185 |
return given, family |
| 1186 |
|
| 1187 |
names = item.reference.get(variable, []) |
| 1188 |
|
| 1189 |
if and_ == 'text': |
| 1190 |
and_term = self.get_single_term(name='and') |
| 1191 |
elif and_ == 'symbol': |
| 1192 |
and_term = self.preformat('&') |
| 1193 |
|
| 1194 |
et_al = self.et_al() |
| 1195 |
output = [] |
| 1196 |
if form == 'count': |
| 1197 |
count = min(len(names), et_al_use_first) |
| 1198 |
output.append(count) |
| 1199 |
return sum(output) |
| 1200 |
else: |
| 1201 |
et_al_truncate = (len(names) > 1 and et_al_min and |
| 1202 |
len(names) >= et_al_min) |
| 1203 |
et_al_last = et_al_use_last and et_al_use_first <= et_al_min - 2 |
| 1204 |
if et_al_truncate: |
| 1205 |
if et_al_last: |
| 1206 |
names = names[:et_al_use_first] + [names[-1]] |
| 1207 |
else: |
| 1208 |
names = names[:et_al_use_first] |
| 1209 |
for i, name in enumerate(names): |
| 1210 |
given, family, dp, ndp, suffix = name.parts() |
| 1211 |
|
| 1212 |
if given is not None and initialize_with is not None: |
| 1213 |
given = self.initialize(given, initialize_with, context) |
| 1214 |
|
| 1215 |
if form == 'long': |
| 1216 |
if (name_as_sort_order == 'all' or |
| 1217 |
(name_as_sort_order == 'first' and i == 0)): |
| 1218 |
if demote_ndp in ('never', 'sort-only'): |
| 1219 |
family = ' '.join([n for n in (ndp, family) if n]) |
| 1220 |
given = ' '.join([n for n in (given, dp) if n]) |
| 1221 |
else: |
| 1222 |
given = ' '.join([n for n in (given, dp, ndp) if n]) |
| 1223 |
|
| 1224 |
given, family = format_name_parts(given, family) |
| 1225 |
order = family, given, suffix |
| 1226 |
text = sort_separator.join([n for n in order if n]) |
| 1227 |
else: |
| 1228 |
family = ' '.join([n for n in (dp, ndp, family) if n]) |
| 1229 |
given, family = format_name_parts(given, family) |
| 1230 |
order = given, family, suffix |
| 1231 |
text = ' '.join([n for n in order if n]) |
| 1232 |
elif form == 'short': |
| 1233 |
family = ' '.join([n for n in (ndp, family) if n]) |
| 1234 |
given, family = format_name_parts(given, family) |
| 1235 |
text = family |
| 1236 |
|
| 1237 |
output.append(text) |
| 1238 |
|
| 1239 |
if et_al_truncate and et_al: |
| 1240 |
if et_al_last: |
| 1241 |
ellipsis = self.unicode_character('horizontal ellipsis') |
| 1242 |
output[-1] = ellipsis + ' ' + output[-1] |
| 1243 |
text = self.join(output, delimiter) |
| 1244 |
elif (delimiter_precedes_et_al == 'always' or |
| 1245 |
(delimiter_precedes_et_al == 'contextual' and |
| 1246 |
len(output) >= 2)): |
| 1247 |
output.append(et_al) |
| 1248 |
text = self.join(output, delimiter) |
| 1249 |
else: |
| 1250 |
text = self.join(output, delimiter) + ' ' + et_al |
| 1251 |
elif and_ is not None and len(output) > 1: |
| 1252 |
text = self.join(output[:-1], ', ') |
| 1253 |
if (delimiter_precedes_last == 'always' or |
| 1254 |
(delimiter_precedes_last == 'contextual' and |
| 1255 |
len(output) > 2)): |
| 1256 |
text = self.join([text, ''], ', ') |
| 1257 |
else: |
| 1258 |
text += ' ' |
| 1259 |
text += '{} '.format(and_term) + output[-1] |
| 1260 |
else: |
| 1261 |
text = self.join(output, delimiter) |
| 1262 |
|
| 1263 |
return text |
| 1264 |
|
| 1265 |
def initialize(self, given, mark, context): |
| 1266 |
if self.get_option('initialize-with-hyphen', context): |
| 1267 |
hyphen_parts = given.split('-') |
| 1268 |
else: |
| 1269 |
hyphen_parts = [given.replace('-', ' ')] |
| 1270 |
|
| 1271 |
result_parts = [] |
| 1272 |
for hyphen_part in hyphen_parts: |
| 1273 |
parts = hyphen_part.replace('.', ' ').split() |
| 1274 |
hyphen_result = '' |
| 1275 |
group = [] |
| 1276 |
for part in parts: |
| 1277 |
if part[0].isupper(): |
| 1278 |
group.append(part[0]) |
| 1279 |
else: |
| 1280 |
# don't initialize particles (which aren't capitalized) |
| 1281 |
hyphen_result += mark.join(group) + mark + ' ' + part + ' ' |
| 1282 |
group = [] |
| 1283 |
hyphen_result += mark.join(group) + mark |
| 1284 |
# remove double spaces |
| 1285 |
hyphen_result = ' '.join(hyphen_result.split()) |
| 1286 |
result_parts.append(hyphen_result) |
| 1287 |
return '-'.join(result_parts) |
| 1288 |
|
| 1289 |
def markup(self, text): |
| 1290 |
if text: |
| 1291 |
return self.wrap(self.format(text)) |
| 1292 |
else: |
| 1293 |
return None |
| 1294 |
|
| 1295 |
|
| 1296 |
class Name_Part(CitationStylesElement, Formatted, Affixed, TextCased): |
| 1297 |
def format_part(self, given, family): |
| 1298 |
if self.get('name') == 'given': |
| 1299 |
given = self.wrap(self.format(self.case(given))) |
| 1300 |
elif self.get('name') == 'family': |
| 1301 |
family = self.wrap(self.format(self.case(family))) |
| 1302 |
return given, family |
| 1303 |
|
| 1304 |
|
| 1305 |
class Et_Al(CitationStylesElement, Formatted, Affixed): |
| 1306 |
def process(self): |
| 1307 |
variable = self.get('term', 'et-al') |
| 1308 |
return self.get_single_term(variable) |
| 1309 |
|
| 1310 |
def markup(self, text): |
| 1311 |
if text: |
| 1312 |
return self.wrap(self.format(text)) |
| 1313 |
else: |
| 1314 |
return None |
| 1315 |
|
| 1316 |
|
| 1317 |
class Substitute(CitationStylesElement, Parent): |
| 1318 |
def render(self, item, context=None, **kwargs): |
| 1319 |
for child in self.getchildren(): |
| 1320 |
try: |
| 1321 |
if isinstance(child, Names) and child.name is None: |
| 1322 |
names = self.xpath_search('./parent::cs:names[1]')[0] |
| 1323 |
text = child.render(item, names_context=names, |
| 1324 |
context=context, **kwargs) |
| 1325 |
else: |
| 1326 |
text = child.render(item, context=context, **kwargs) |
| 1327 |
except VariableError: |
| 1328 |
continue |
| 1329 |
if text: |
| 1330 |
self.add_to_repressed_list(child, context) |
| 1331 |
break |
| 1332 |
try: |
| 1333 |
return text |
| 1334 |
except NameError: |
| 1335 |
return None |
| 1336 |
|
| 1337 |
def add_to_repressed_list(self, child, context): |
| 1338 |
layout = context.get_layout() |
| 1339 |
tag_list = layout.repressed.get(child.tag, []) |
| 1340 |
tag_list.append(child.get('variable')) |
| 1341 |
layout.repressed[child.tag] = tag_list |
| 1342 |
|
| 1343 |
|
| 1344 |
class Label(CitationStylesElement, Formatted, Affixed, StrippedPeriods, |
| 1345 |
TextCased): |
| 1346 |
def calls_variable(self): |
| 1347 |
return self.get('variable') == 'locator' |
| 1348 |
|
| 1349 |
def process(self, item, variable=None, plural=None, context=None, **kwargs): |
| 1350 |
if variable is None: |
| 1351 |
variable = self.get('variable') |
| 1352 |
form = self.get('form', 'long') |
| 1353 |
plural_option = self.get('plural', 'contextual') |
| 1354 |
if plural is None: |
| 1355 |
plural = self._is_plural(item) |
| 1356 |
|
| 1357 |
if variable == 'locator' and item.has_locator: |
| 1358 |
variable = item.locator.label |
| 1359 |
|
| 1360 |
if (plural_option == 'contextual' and plural or |
| 1361 |
plural_option == 'always'): |
| 1362 |
text = self.get_plural_term(name=variable, |
| 1363 |
form=form if form != 'long' else None) |
| 1364 |
else: |
| 1365 |
text = self.get_single_term(name=variable, |
| 1366 |
form=form if form != 'long' else None) |
| 1367 |
|
| 1368 |
return text |
| 1369 |
|
| 1370 |
def markup(self, text): |
| 1371 |
if text: |
| 1372 |
return self.wrap(self.format(self.case(self.strip_periods(text)))) |
| 1373 |
else: |
| 1374 |
return None |
| 1375 |
|
| 1376 |
# Content is plural when it holds multiple numbers separated by a list or |
| 1377 |
# range separator (e.g. "1, 2" or "1-3"). A period is not such a separator: |
| 1378 |
# it is part of a single dotted number/version (e.g. "2.0"), which stays |
| 1379 |
# singular ("Version 2.0", not "Versions 2.0"). |
| 1380 |
RE_MULTIPLE_NUMBERS = re.compile(r'\d+[^\d.]+\d+') |
| 1381 |
|
| 1382 |
def _is_plural(self, item): |
| 1383 |
variable = self.get('variable') |
| 1384 |
if variable == 'locator': |
| 1385 |
value = item.locator.identifier |
| 1386 |
else: |
| 1387 |
try: |
| 1388 |
value = item.reference[variable.replace('-', '_')] |
| 1389 |
except VariableError: |
| 1390 |
return False |
| 1391 |
|
| 1392 |
if variable.startswith('number-of') and int(item[variable]) > 1: |
| 1393 |
return True |
| 1394 |
else: |
| 1395 |
return self.RE_MULTIPLE_NUMBERS.search(str(value)) is not None |
| 1396 |
|
| 1397 |
|
| 1398 |
class Group(CitationStylesElement, Parent, Formatted, Affixed, Delimited): |
| 1399 |
def calls_variable(self): |
| 1400 |
return True |
| 1401 |
|
| 1402 |
def process(self, item, context=None, **kwargs): |
| 1403 |
output = [] |
| 1404 |
variable_called = False |
| 1405 |
variable_rendered = False |
| 1406 |
# A `cs:group` delimiter also delimits the children of a transparent |
| 1407 |
# `cs:choose` child, so pass it down (see `Parent.render_children`). |
| 1408 |
delimiter = self.get('delimiter', '') |
| 1409 |
for child in self.iterchildren(): |
| 1410 |
variable_called = variable_called or child.calls_variable() |
| 1411 |
try: |
| 1412 |
if isinstance(child, Choose): |
| 1413 |
child_text = child.render(item, context=context, |
| 1414 |
delimiter=delimiter, **kwargs) |
| 1415 |
else: |
| 1416 |
child_text = child.render(item, context=context, **kwargs) |
| 1417 |
if child_text is not None: |
| 1418 |
output.append(child_text) |
| 1419 |
variable_rendered = (variable_rendered or |
| 1420 |
child.calls_variable()) |
| 1421 |
except VariableError: |
| 1422 |
pass |
| 1423 |
output = [item for item in output if item is not None] |
| 1424 |
success = not variable_called or (variable_called and variable_rendered) |
| 1425 |
if output and success: |
| 1426 |
return self.join(output) |
| 1427 |
else: |
| 1428 |
raise VariableError |
| 1429 |
|
| 1430 |
def markup(self, text): |
| 1431 |
if text: |
| 1432 |
return self.wrap(self.format(text)) |
| 1433 |
else: |
| 1434 |
return None |
| 1435 |
|
| 1436 |
|
| 1437 |
class ConditionFailed(Exception): |
| 1438 |
pass |
| 1439 |
|
| 1440 |
|
| 1441 |
class Choose(CitationStylesElement, Parent): |
| 1442 |
def render(self, item, context=None, delimiter='', **kwargs): |
| 1443 |
# `cs:choose` is transparent: the delimiter of the enclosing element is |
| 1444 |
# forwarded to the children of the matching branch. |
| 1445 |
for child in self.getchildren(): |
| 1446 |
try: |
| 1447 |
return child.render(item, context=context, |
| 1448 |
delimiter=delimiter, **kwargs) |
| 1449 |
except ConditionFailed: |
| 1450 |
continue |
| 1451 |
|
| 1452 |
return None |
| 1453 |
|
| 1454 |
|
| 1455 |
class If(CitationStylesElement, Parent): |
| 1456 |
def render(self, item, context=None, delimiter='', **kwargs): |
| 1457 |
# TODO self.get('disambiguate') |
| 1458 |
results = [] |
| 1459 |
if 'type' in self.attrib: |
| 1460 |
results += self._type(item) |
| 1461 |
if 'variable' in self.attrib: |
| 1462 |
results += self._variable(item) |
| 1463 |
if 'is-numeric' in self.attrib: |
| 1464 |
results += self._is_numeric(item) |
| 1465 |
if 'is-uncertain-date' in self.attrib: |
| 1466 |
results += self._is_uncertain_date(item) |
| 1467 |
if 'locator' in self.attrib: |
| 1468 |
results += self._locator(item) |
| 1469 |
if 'position' in self.attrib: |
| 1470 |
results += self._position(item, context) |
| 1471 |
|
| 1472 |
# TODO: 'match' also applies to individual tests above! |
| 1473 |
if self.get('match') == 'any': |
| 1474 |
result = any(results) |
| 1475 |
elif self.get('match') == 'none': |
| 1476 |
result = not any(results) |
| 1477 |
else: |
| 1478 |
result = all(results) |
| 1479 |
|
| 1480 |
if not result: |
| 1481 |
raise ConditionFailed |
| 1482 |
|
| 1483 |
return self.render_children(item, context=context, |
| 1484 |
delimiter=delimiter, **kwargs) |
| 1485 |
|
| 1486 |
def _type(self, item): |
| 1487 |
return [typ.lower() == item.reference.type |
| 1488 |
for typ in self.get('type').split()] |
| 1489 |
|
| 1490 |
def _variable(self, item): |
| 1491 |
variables = [var.replace('-', '_') |
| 1492 |
for var in self.get('variable').split()] |
| 1493 |
output = [] |
| 1494 |
for variable in variables: |
| 1495 |
if variable == 'locator': |
| 1496 |
output.append('locator' in item) |
| 1497 |
else: |
| 1498 |
output.append(variable in item.reference) |
| 1499 |
return output |
| 1500 |
|
| 1501 |
re_numeric = re.compile(r'^([A-Z]*\d+[A-Z]*)$', re.I) |
| 1502 |
|
| 1503 |
def _is_numeric(self, item): |
| 1504 |
numeric_match = self.re_numeric.match |
| 1505 |
return [var.replace('-', '_') in item.reference and |
| 1506 |
numeric_match(str(item.reference[var.replace('-', '_')])) |
| 1507 |
for var in self.get('is-numeric').split()] |
| 1508 |
|
| 1509 |
def _is_uncertain_date(self, item): |
| 1510 |
result = [] |
| 1511 |
for date in self.get('is-uncertain-date').split(): |
| 1512 |
date_variable = date.replace('-', '_') |
| 1513 |
try: |
| 1514 |
circa = item.reference[date_variable].get('circa', False) |
| 1515 |
except VariableError: |
| 1516 |
circa = False |
| 1517 |
except AttributeError: |
| 1518 |
circa = False |
| 1519 |
result.append(circa) |
| 1520 |
return result |
| 1521 |
|
| 1522 |
def _locator(self, item): |
| 1523 |
return [item.has_locator and var.replace('-', ' ') == item.locator.label |
| 1524 |
for var in self.get('locator').split()] |
| 1525 |
|
| 1526 |
def _position(self, item, context): |
| 1527 |
if context is None: |
| 1528 |
context = self |
| 1529 |
if context.xpath_search('./ancestor::*[self::cs:bibliography]'): |
| 1530 |
return [False] |
| 1531 |
# citation node |
| 1532 |
cites = context.get_layout().getparent().cites |
| 1533 |
last_cite = cites[-1] if cites else None |
| 1534 |
already_cited = item.key in (cite.key for cite in cites) |
| 1535 |
possibly_ibid = (already_cited |
| 1536 |
and item.key == last_cite.key |
| 1537 |
and (item.citation is last_cite.citation |
| 1538 |
or len(last_cite.citation.cites) == 1)) |
| 1539 |
results = [] |
| 1540 |
for position in self.get('position').split(): |
| 1541 |
result = False |
| 1542 |
if position == 'first': |
| 1543 |
result = not already_cited |
| 1544 |
elif position == 'subsequent': |
| 1545 |
result = already_cited |
| 1546 |
elif possibly_ibid and position == 'ibid': |
| 1547 |
result = item.has_locator or not last_cite.has_locator |
| 1548 |
elif possibly_ibid and position == 'ibid-with-locator': |
| 1549 |
result = (item.has_locator and not last_cite.has_locator |
| 1550 |
or (item.has_locator and last_cite.has_locator |
| 1551 |
and item.locator != last_cite.locator)) |
| 1552 |
elif already_cited and position == 'near-note': |
| 1553 |
max_distance = self.get_root().get_option('near-note-distance') |
| 1554 |
citations = 1 |
| 1555 |
last_citation = None |
| 1556 |
for cite in reversed(cites): |
| 1557 |
if item.key == cite.key and citations <= max_distance: |
| 1558 |
result = True |
| 1559 |
break |
| 1560 |
elif cite.citation is not last_citation: |
| 1561 |
citations += 1 |
| 1562 |
last_citation = cite.citation |
| 1563 |
results.append(result) |
| 1564 |
return results |
| 1565 |
|
| 1566 |
|
| 1567 |
class Else_If(If, CitationStylesElement): |
| 1568 |
pass |
| 1569 |
|
| 1570 |
|
| 1571 |
class Else(CitationStylesElement, Parent): |
| 1572 |
def render(self, item, context=None, delimiter='', **kwargs): |
| 1573 |
return self.render_children(item, context=context, |
| 1574 |
delimiter=delimiter, **kwargs) |
| 1575 |
|
| 1576 |
|
| 1577 |
# utility functions |
| 1578 |
|
| 1579 |
def to_ordinal(number, context): |
| 1580 |
def _find_ordinal(fallback_locale): |
| 1581 |
if len(str(number)) == 1: |
| 1582 |
ordinal_term = f'ordinal-{number:02}' |
| 1583 |
else: |
| 1584 |
ordinal_term = f'ordinal-{number}' |
| 1585 |
|
| 1586 |
if (term := context.get_single_term(name=ordinal_term, |
| 1587 |
fallback_locale=fallback_locale, |
| 1588 |
zero_padded=False)): |
| 1589 |
return term |
| 1590 |
|
| 1591 |
ordinal_term = f'ordinal-{int(str(number)[-1]):02}' |
| 1592 |
if (term := context.get_single_term(name=ordinal_term, |
| 1593 |
fallback_locale=fallback_locale, |
| 1594 |
zero_padded=True)): |
| 1595 |
return term |
| 1596 |
|
| 1597 |
return context.get_single_term(name='ordinal', |
| 1598 |
fallback_locale=fallback_locale, |
| 1599 |
zero_padded=False) |
| 1600 |
|
| 1601 |
result = _find_ordinal(fallback_locale=False) |
| 1602 |
if not result: |
| 1603 |
result = _find_ordinal(fallback_locale=True) |
| 1604 |
return str(number) + result |
| 1605 |
|
| 1606 |
def romanize(n): |
| 1607 |
# by Kay Schluehr - from http://billmill.org/python_roman.html |
| 1608 |
numerals = (('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), |
| 1609 |
('C', 100),('XC', 90),('L', 50),('XL', 40), ('X', 10), |
| 1610 |
('IX', 9), ('V', 5), ('IV', 4), ('I', 1)) |
| 1611 |
roman = [] |
| 1612 |
for ltr, num in numerals: |
| 1613 |
(k, n) = divmod(n, num) |
| 1614 |
roman.append(ltr * k) |
| 1615 |
return ''.join(roman) |