www

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | Submodules | README | LICENSE

commit 557140a0226c449cf9ee0d45ea612d05ccecdb0f
parent c11268533840840d90bb088914e75179453b2e18
Author: Simon Kornblith <simon@simonster.com>
Date:   Tue, 23 Apr 2013 14:38:51 -0400

Update citeproc-js to 1.0.455

Diffstat:
Mchrome/content/zotero/xpcom/citeproc.js | 7727+++++++++++++++++++++++++++++++++++++++----------------------------------------
1 file changed, 3828 insertions(+), 3899 deletions(-)

diff --git a/chrome/content/zotero/xpcom/citeproc.js b/chrome/content/zotero/xpcom/citeproc.js @@ -57,7 +57,7 @@ if (!Array.indexOf) { }; } var CSL = { - PROCESSOR_VERSION: "1.0.451", + PROCESSOR_VERSION: "1.0.455", CONDITION_LEVEL_TOP: 1, CONDITION_LEVEL_BOTTOM: 2, PLAIN_HYPHEN_REGEX: /(?:[^\\]-|\u2013)/, @@ -292,6 +292,7 @@ var CSL = { "chapter-number", "collection-number", "edition", + "page", "issue", "locator", "number", @@ -930,6 +931,20 @@ CSL_CHROME.prototype.flagDateMacros = function(myxml) { } } }; +var XML_PARSING; +if ("undefined" !== typeof CSL_IS_NODEJS) { + XML_PARSING = CSL_NODEJS; +} else if ("undefined" !== typeof CSL_E4X) { + XML_PARSING = CSL_E4X; +} else if ("undefined" !== typeof CSL_JSON) { + XML_PARSING = CSL_JSON; +} else { + XML_PARSING = CSL_CHROME; +} +CSL.System = {}; +CSL.System.Xml = { + "Parsing": XML_PARSING +}; CSL.getSortCompare = function () { if (CSL.stringCompare) { return CSL.stringCompare; @@ -986,2260 +1001,2344 @@ CSL.getSortCompare = function () { } return sortCompare; }; -CSL.Output = {}; -CSL.Output.Queue = function (state) { - this.levelname = ["top"]; - this.state = state; - this.queue = []; - this.empty = new CSL.Token("empty"); - var tokenstore = {}; - tokenstore.empty = this.empty; - this.formats = new CSL.Stack(tokenstore); - this.current = new CSL.Stack(this.queue); -}; -CSL.Output.Queue.prototype.pop = function () { - var drip = this.current.value(); - if (drip.length) { - return drip.pop(); +CSL.ambigConfigDiff = function(a, b) { + var ret, pos, len, ppos, llen; + if (a.names.length !== b.names.length) { + return 1; } else { - return drip.blobs.pop(); - } -}; -CSL.Output.Queue.prototype.getToken = function (name) { - var ret = this.formats.value()[name]; - return ret; -}; -CSL.Output.Queue.prototype.mergeTokenStrings = function (base, modifier) { - var base_token, modifier_token, ret, key; - base_token = this.formats.value()[base]; - modifier_token = this.formats.value()[modifier]; - ret = base_token; - if (modifier_token) { - if (!base_token) { - base_token = new CSL.Token(base, CSL.SINGLETON); - base_token.decorations = []; - } - ret = new CSL.Token(base, CSL.SINGLETON); - key = ""; - for (key in base_token.strings) { - if (base_token.strings.hasOwnProperty(key)) { - ret.strings[key] = base_token.strings[key]; - } - } - for (key in modifier_token.strings) { - if (modifier_token.strings.hasOwnProperty(key)) { - ret.strings[key] = modifier_token.strings[key]; + for (pos = 0, len = a.names.length; pos < len; pos += 1) { + if (a.names[pos] !== b.names[pos]) { + return 1; + } else { + for (ppos = 0, llen = a.givens[pos]; ppos < llen; ppos += 1) { + if (a.givens[pos][ppos] !== b.givens[pos][ppos]) { + return 1; + } + } } } - ret.decorations = base_token.decorations.concat(modifier_token.decorations); } - return ret; + if (a.disambiguate != b.disambiguate) { + return 1; + } + if (a.year_suffix !== b.year_suffix) { + return 1; + } + return 0; }; -CSL.Output.Queue.prototype.addToken = function (name, modifier, token) { - var newtok, attr; - newtok = new CSL.Token("output"); - if ("string" === typeof token) { - token = this.formats.value()[token]; +CSL.cloneAmbigConfig = function (config, oldconfig, tainters) { + var i, ilen, j, jlen, k, klen, param; + var ret = {}; + ret.names = []; + ret.givens = []; + ret.year_suffix = false; + ret.disambiguate = false; + for (i = 0, ilen = config.names.length; i < ilen; i += 1) { + param = config.names[i]; + ret.names[i] = param; } - if (token && token.strings) { - for (attr in token.strings) { - if (token.strings.hasOwnProperty(attr)) { - newtok.strings[attr] = token.strings[attr]; - } + for (i = 0, ilen = config.givens.length; i < ilen; i += 1) { + param = []; + for (j = 0, jlen = config.givens[i].length; j < jlen; j += 1) { + param.push(config.givens[i][j]); } - newtok.decorations = token.decorations; + ret.givens.push(param); } - if ("string" === typeof modifier) { - newtok.strings.delimiter = modifier; + if (oldconfig) { + ret.year_suffix = oldconfig.year_suffix; + ret.disambiguate = oldconfig.disambiguate; + } else { + ret.year_suffix = config.year_suffix; + ret.disambiguate = config.disambiguate; } - this.formats.value()[name] = newtok; + return ret; }; -CSL.Output.Queue.prototype.pushFormats = function (tokenstore) { - if (!tokenstore) { - tokenstore = {}; +CSL.getAmbigConfig = function () { + var config, ret; + config = this.tmp.disambig_request; + if (!config) { + config = this.tmp.disambig_settings; } - tokenstore.empty = this.empty; - this.formats.push(tokenstore); + ret = CSL.cloneAmbigConfig(config); + return ret; }; -CSL.Output.Queue.prototype.popFormats = function (tokenstore) { - this.formats.pop(); +CSL.getMaxVals = function () { + return this.tmp.names_max.mystack.slice(); }; -CSL.Output.Queue.prototype.startTag = function (name, token) { - var tokenstore = {}; - if (this.state.tmp["doing-macro-with-date"] && this.state.tmp.extension) { - token = this.empty; - name = "empty"; - } - tokenstore[name] = token; - this.pushFormats(tokenstore); - this.openLevel(name); +CSL.getMinVal = function () { + return this.tmp["et-al-min"]; }; -CSL.Output.Queue.prototype.endTag = function (name) { - this.closeLevel(); - this.popFormats(); +CSL.tokenExec = function (token, Item, item) { + var next, maybenext, exec, pos, len, debug; + debug = false; + next = token.next; + maybenext = false; + if (token.evaluator) { + next = token.evaluator(token, this, Item, item); + } + len = token.execs.length; + for (pos = 0; pos < len; pos += 1) { + exec = token.execs[pos]; + maybenext = exec.call(token, this, Item, item); + if (maybenext) { + next = maybenext; + } + } + return next; }; -CSL.Output.Queue.prototype.openLevel = function (token, ephemeral) { - var blob, curr, x, has_ephemeral; - if ("object" === typeof token) { - blob = new CSL.Blob(undefined, token); - } else if ("undefined" === typeof token) { - blob = new CSL.Blob(undefined, this.formats.value().empty, "empty"); +CSL.expandMacro = function (macro_key_token) { + var mkey, start_token, key, end_token, navi, macro_nodes, newoutput, mergeoutput, end_of_macro, func; + mkey = macro_key_token.postponed_macro; + if (this.build.macro_stack.indexOf(mkey) > -1) { + throw "CSL processor error: call to macro \"" + mkey + "\" would cause an infinite loop"; } else { - if (!this.formats.value() || !this.formats.value()[token]) { - throw "CSL processor error: call to nonexistent format token \"" + token + "\""; - } - blob = new CSL.Blob(undefined, this.formats.value()[token], token); + this.build.macro_stack.push(mkey); } - if (this.nestedBraces) { - blob.strings.prefix = blob.strings.prefix.replace(this.nestedBraces[0][0], this.nestedBraces[0][1]); - blob.strings.prefix = blob.strings.prefix.replace(this.nestedBraces[1][0], this.nestedBraces[1][1]); - blob.strings.suffix = blob.strings.suffix.replace(this.nestedBraces[0][0], this.nestedBraces[0][1]); - blob.strings.suffix = blob.strings.suffix.replace(this.nestedBraces[1][0], this.nestedBraces[1][1]); + var hasDate = false; + var macroid = false; + macro_nodes = this.sys.xml.getNodesByName(this.cslXml, 'macro', mkey); + if (macro_nodes.length) { + macroid = this.sys.xml.getAttributeValue(macro_nodes[0],'cslid'); + hasDate = this.sys.xml.getAttributeValue(macro_nodes[0], "macro-has-date"); } - curr = this.current.value(); - curr.push(blob); - this.current.push(blob); -}; -CSL.Output.Queue.prototype.closeLevel = function (name) { - if (name && name !== this.current.value().levelname) { - CSL.error("Level mismatch error: wanted " + name + " but found " + this.current.value().levelname); + if (hasDate) { + func = function (state, Item) { + if (state.tmp.extension) { + state.tmp["doing-macro-with-date"] = true; + } + }; + macro_key_token.execs.push(func); } - this.current.pop(); -}; -CSL.Output.Queue.prototype.append = function (str, tokname, notSerious, ignorePredecessor, noStripPeriods) { - var token, blob, curr; - var useblob = true; - if (notSerious) { - ignorePredecessor = true; + macro_key_token.tokentype = CSL.START; + macro_key_token.cslid = macroid; + CSL.Node.group.build.call(macro_key_token, this, this[this.build.area].tokens, true); + if (!this.sys.xml.getNodeValue(macro_nodes)) { + throw "CSL style error: undefined macro \"" + mkey + "\""; } - if (this.state.tmp["doing-macro-with-date"]) { - if (tokname !== "macro-with-date") { - return false; - } - if (tokname === "macro-with-date") { - tokname = "empty"; - } + navi = new this.getNavi(this, macro_nodes); + CSL.buildStyle.call(this, navi); + end_of_macro = new CSL.Token("group", CSL.END); + if (macro_key_token.decorations) { + end_of_macro.decorations = macro_key_token.decorations.slice(); } - if ("undefined" === typeof str) { - return false; + if (hasDate) { + func = function (state, Item) { + if (state.tmp.extension) { + state.tmp["doing-macro-with-date"] = false; + } + }; + end_of_macro.execs.push(func); } - if ("number" === typeof str) { - str = "" + str; + CSL.Node.group.build.call(end_of_macro, this, this[this.build.area].tokens, true); + this.build.macro_stack.pop(); +}; +CSL.XmlToToken = function (state, tokentype) { + var name, txt, attrfuncs, attributes, decorations, token, key, target; + name = state.sys.xml.nodename(this); + if (state.build.skip && state.build.skip !== name) { + return; } - if (!notSerious - && this.state.tmp.element_trace - && this.state.tmp.element_trace.value() === "suppress-me") { - return false; + if (!name) { + txt = state.sys.xml.content(this); + if (txt) { + state.build.text = txt; + } + return; } - blob = false; - if (!tokname) { - token = this.formats.value().empty; - } else if (tokname === "literal") { - token = true; - useblob = false; - } else if ("string" === typeof tokname) { - token = this.formats.value()[tokname]; - } else { - token = tokname; - } - if (!token) { - throw "CSL processor error: unknown format token name: " + tokname; - } - if (token.strings && "undefined" === typeof token.strings.delimiter) { - token.strings.delimiter = ""; - } - if ("string" === typeof str && str.length) { - str = str.replace(/ ([:;?!\u00bb])/g, "\u202f$1").replace(/\u00ab /g, "\u00ab\u202f"); - this.last_char_rendered = str.slice(-1); - str = str.replace(/\s+'/g, " \'").replace(/^'/g, " \'"); - if (!ignorePredecessor) { - this.state.tmp.term_predecessor = true; - } else if (notSerious) { - this.state.tmp.term_predecessor_name = true; - } - } - blob = new CSL.Blob(str, token); - if (this.nestedBraces) { - blob.strings.prefix = blob.strings.prefix.replace(this.nestedBraces[0][0], this.nestedBraces[0][1]); - blob.strings.prefix = blob.strings.prefix.replace(this.nestedBraces[1][0], this.nestedBraces[1][1]); - blob.strings.suffix = blob.strings.suffix.replace(this.nestedBraces[0][0], this.nestedBraces[0][1]); - blob.strings.suffix = blob.strings.suffix.replace(this.nestedBraces[1][0], this.nestedBraces[1][1]); - } - curr = this.current.value(); - if ("undefined" === typeof curr && this.current.mystack.length === 0) { - this.current.mystack.push([]); - curr = this.current.value(); - } - if ("string" === typeof blob.blobs) { - if (!ignorePredecessor) { - this.state.tmp.term_predecessor = true; - } else if (notSerious) { - this.state.tmp.term_predecessor_name = true; - } - } - if (!notSerious) { - this.state.parallel.AppendBlobPointer(curr); + if (!CSL.Node[state.sys.xml.nodename(this)]) { + throw "Undefined node name \"" + name + "\"."; } - if ("string" === typeof str) { - curr.push(blob); - if (blob.strings["text-case"]) { - blob.blobs = CSL.Output.Formatters[blob.strings["text-case"]](this.state, str); - } - if (this.state.tmp.strip_periods && !noStripPeriods) { - blob.blobs = blob.blobs.replace(/\.([^a-z]|$)/g, "$1"); - } - for (var i = blob.decorations.length - 1; i > -1; i += -1) { - if (blob.decorations[i][0] === "@quotes" && blob.decorations[i][1] === "true") { - blob.punctuation_in_quote = this.state.getOpt("punctuation-in-quote") - } - if (!blob.blobs.match(CSL.ROMANESQUE_REGEXP)) { - if (blob.decorations[i][0] === "@font-style") { - blob.decorations = blob.decorations.slice(0, i).concat(blob.decorations.slice(i + 1)); + attrfuncs = []; + attributes = state.sys.xml.attributes(this); + decorations = CSL.setDecorations.call(this, state, attributes); + token = new CSL.Token(name, tokentype); + if (tokentype !== CSL.END || name === "if" || name === "else-if" || name === "layout") { + for (key in attributes) { + if (attributes.hasOwnProperty(key)) { + if (tokentype === CSL.END && key !== "@language" && key !== "@locale") { + continue; + } + if (attributes.hasOwnProperty(key)) { + if (CSL.Attributes[key]) { + try { + CSL.Attributes[key].call(token, state, "" + attributes[key]); + } catch (e) { + CSL.error(e); + throw "CSL processor error, " + key + " attribute: " + e; + } + } else { + CSL.debug("warning: undefined attribute \""+key+"\" in style"); + } } } } - this.state.fun.flipflopper.init(str, blob); - this.state.fun.flipflopper.processTags(); - } else if (useblob) { - curr.push(blob); - } else { - curr.push(str); + token.decorations = decorations; } - return true; + target = state[state.build.area].tokens; + CSL.Node[name].build.call(token, state, target); }; -CSL.Output.Queue.prototype.string = function (state, myblobs, blob) { - var i, ilen, j, jlen, b; - var txt_esc = CSL.getSafeEscape(this.state); - var blobs = myblobs.slice(); - var ret = []; - if (blobs.length === 0) { - return ret; +CSL.DateParser = function () { + var jiy_list, jiy, jiysplitter, jy, jmd, jr, pos, key, val, yearlast, yearfirst, number, rangesep, fuzzychar, chars, rex, rexdash, rexdashslash, rexslashdash, seasonstrs, seasonrexes, seasonstr, monthstrs, monthstr, mrexes, seasonrex, len, jiymatchstring, jiymatcher; + jiy_list = [ + ["\u660E\u6CBB", 1867], + ["\u5927\u6B63", 1911], + ["\u662D\u548C", 1925], + ["\u5E73\u6210", 1988] + ]; + jiy = {}; + len = jiy_list.length; + for (pos = 0; pos < len; pos += 1) { + key = jiy_list[pos][0]; + val = jiy_list[pos][1]; + jiy[key] = val; } - var blob_delimiter = ""; - if (blob) { - blob_delimiter = blob.strings.delimiter; - } else { - state.tmp.count_offset_characters = false; - state.tmp.offset_characters = 0; + jiymatchstring = []; + for (pos = 0; pos < len; pos += 1) { + val = jiy_list[pos][0]; + jiymatchstring.push(val); } - if (blob && blob.new_locale) { - blob.old_locale = state.opt.lang; - state.opt.lang = blob.new_locale; + jiymatchstring = jiymatchstring.join("|"); + jiysplitter = "(?:" + jiymatchstring + ")(?:[0-9]+)"; + jiysplitter = new RegExp(jiysplitter); + jiymatcher = "(?:" + jiymatchstring + ")(?:[0-9]+)"; + jiymatcher = new RegExp(jiymatcher, "g"); + jmd = /(\u6708|\u5E74)/g; + jy = /\u65E5/; + jr = /\u301c/g; + yearlast = "(?:[?0-9]{1,2}%%NUMD%%){0,2}[?0-9]{4}(?![0-9])"; + yearfirst = "[?0-9]{4}(?:%%NUMD%%[?0-9]{1,2}){0,2}(?![0-9])"; + number = "[?0-9]{1,3}"; + rangesep = "[%%DATED%%]"; + fuzzychar = "[?~]"; + chars = "[a-zA-Z]+"; + rex = "(" + yearfirst + "|" + yearlast + "|" + number + "|" + rangesep + "|" + fuzzychar + "|" + chars + ")"; + rexdash = new RegExp(rex.replace(/%%NUMD%%/g, "-").replace(/%%DATED%%/g, "-")); + rexdashslash = new RegExp(rex.replace(/%%NUMD%%/g, "-").replace(/%%DATED%%/g, "\/")); + rexslashdash = new RegExp(rex.replace(/%%NUMD%%/g, "\/").replace(/%%DATED%%/g, "-")); + seasonstrs = []; + seasonrexes = []; + len = seasonstrs.length; + for (pos = 0; pos < len; pos += 1) { + seasonrex = new RegExp(seasonstrs[pos] + ".*"); + seasonrexes.push(seasonrex); } - var blobjr, use_suffix, use_prefix, params; - for (i = 0, ilen = blobs.length; i < ilen; i += 1) { - blobjr = blobs[i]; - if (blobjr.strings.first_blob) { - state.tmp.count_offset_characters = blobjr.strings.first_blob; + this.mstrings = "january february march april may june july august september october november december spring summer fall winter spring summer"; + this.mstrings = this.mstrings.split(" "); + this.setOrderDayMonth = function() { + this.monthguess = 1; + this.dayguess = 0; + }; + this.setOrderMonthDay = function() { + this.monthguess = 0; + this.dayguess = 1; + }; + this.setOrderMonthDay(); + this.resetMonths = function() { + var i, ilen, j, jlen; + this.msets = []; + for (i = 0, ilen = this.mstrings.length; i < ilen; i += 1) { + this.msets.push([this.mstrings[i]]); } - if ("string" === typeof blobjr.blobs) { - if ("number" === typeof blobjr.num) { - ret.push(blobjr); - } else if (blobjr.blobs) { - b = txt_esc(blobjr.blobs); - var blen = b.length; - if (!state.tmp.suppress_decorations) { - for (j = 0, jlen = blobjr.decorations.length; j < jlen; j += 1) { - params = blobjr.decorations[j]; - if (params[0] === "@showid") { - continue; + this.mabbrevs = []; + for (i = 0, ilen = this.msets.length; i < ilen; i += 1) { + this.mabbrevs.push([]); + for (j = 0, jlen = this.msets[i].length; j < jlen; j += 1) { + this.mabbrevs[i].push(this.msets[i][0].slice(0, 3)); + } + } + this.mrexes = []; + for (i = 0, ilen = this.mabbrevs.length; i < ilen; i += 1) { + this.mrexes.push(new RegExp("(?:" + this.mabbrevs[i].join("|") + ")")); + } + }; + this.resetMonths(); + this.addMonths = function(lst) { + var i, ilen, j, jlen, k, klen, jkey, kkey; + if ("string" === typeof lst) { + lst = lst.split(/\s+/); + } + if (lst.length !== 12 && lst.length !== 16) { + CSL.debug("month [+season] list of "+lst.length+", expected 12 or 16. Ignoring."); + return; + } + var othermatch = []; + var thismatch = []; + for (i = 0, ilen = lst.length; i < ilen; i += 1) { + var abbrevlen = false; + var skip = false; + var insert = 3; + var extend = {}; + for (j = 0, jlen = this.mabbrevs.length; j < jlen; j += 1) { + extend[j] = {}; + if (j === i) { + for (k = 0, klen = this.mabbrevs[i].length; k < klen; k += 1) { + if (this.mabbrevs[i][k] === lst[i].slice(0, this.mabbrevs[i][k].length)) { + skip = true; + break; } - if (state.normalDecorIsOrphan(blobjr, params)) { - continue; + } + } else { + for (k = 0, klen = this.mabbrevs[j].length; k < klen; k += 1) { + abbrevlen = this.mabbrevs[j][k].length; + if (this.mabbrevs[j][k] === lst[i].slice(0, abbrevlen)) { + while (this.msets[j][k].slice(0, abbrevlen) === lst[i].slice(0, abbrevlen)) { + if (abbrevlen > lst[i].length || abbrevlen > this.msets[j][k].length) { + CSL.debug("unable to disambiguate month string in date parser: "+lst[i]); + break; + } else { + abbrevlen += 1; + } + } + insert = abbrevlen; + extend[j][k] = abbrevlen; } - b = state.fun.decorate[params[0]][params[1]](state, b, params[2]); } } - if (b && b.length) { - b = txt_esc(blobjr.strings.prefix, state.tmp.nestedBraces) + b + txt_esc(blobjr.strings.suffix, state.tmp.nestedBraces); - if (state.opt.development_extensions.csl_reverse_lookup_support && !state.tmp.suppress_decorations) { - for (j = 0, jlen = blobjr.decorations.length; j < jlen; j += 1) { - params = blobjr.decorations[j]; - if (params[0] === "@showid") { - b = state.fun.decorate[params[0]][params[1]](state, b, params[2]); + for (jkey in extend) { + if (extend.hasOwnProperty(jkey)) { + for (kkey in extend[jkey]) { + if (extend[jkey].hasOwnProperty(kkey)) { + abbrevlen = extend[jkey][kkey]; + jkey = parseInt(jkey, 10); + kkey = parseInt(kkey, 10); + this.mabbrevs[jkey][kkey] = this.msets[jkey][kkey].slice(0, abbrevlen); } } } - ret.push(b); - if (state.tmp.count_offset_characters) { - state.tmp.offset_characters += (blen + blobjr.strings.suffix.length + blobjr.strings.prefix.length); - } } } - } else if (blobjr.blobs.length) { - var addtoret = state.output.string(state, blobjr.blobs, blobjr); - ret = ret.concat(addtoret); - } - if (blobjr.strings.first_blob) { - state.registry.registry[blobjr.strings.first_blob].offset = state.tmp.offset_characters; - state.tmp.count_offset_characters = false; + if (!skip) { + this.msets[i].push(lst[i]); + this.mabbrevs[i].push(lst[i].slice(0, insert)); + } } - } - for (i=0,ilen=ret.length - 1;i<ilen;i+=1) { - if ("number" === typeof ret[i].num && "number" === typeof ret[i+1].num && !ret[i+1].UGLY_DELIMITER_SUPPRESS_HACK) { - ret[i].strings.suffix = txt_esc(blob_delimiter); - ret[i+1].successor_prefix = ""; - ret[i+1].UGLY_DELIMITER_SUPPRESS_HACK = true; + this.mrexes = []; + for (i = 0, ilen = this.mabbrevs.length; i < ilen; i += 1) { + this.mrexes.push(new RegExp("(?:" + this.mabbrevs[i].join("|") + ")")); } - } - var span_split = 0; - for (i = 0, ilen = ret.length; i < ilen; i += 1) { - if ("string" === typeof ret[i]) { - span_split = (parseInt(i, 10) + 1); - if (i < ret.length - 1 && "object" === typeof ret[i + 1]) { - if (blob_delimiter && !ret[i + 1].UGLY_DELIMITER_SUPPRESS_HACK) { - ret[i] += txt_esc(blob_delimiter); + }; + this.parse = function (txt) { + var slash, dash, lst, l, m, number, note, thedate, slashcount, range_delim, date_delim, ret, delim_pos, delims, isrange, suff, date, breakme, item, delim, element, mm, slst, mmpos, i, ilen, j, jlen, k, klen; + if (txt) { + txt = "" + txt; + txt = txt.replace(/\s*[0-9]{2}:[0-9]{2}(?::[0-9]+)/,""); + m = txt.match(jmd); + if (m) { + txt = txt.replace(/\s+/, "", "g"); + txt = txt.replace(jy, "", "g"); + txt = txt.replace(jmd, "-", "g"); + txt = txt.replace(jr, "/", "g"); + txt = txt.replace("-/", "/", "g"); + txt = txt.replace(/-$/,"", "g"); + slst = txt.split(jiysplitter); + lst = []; + mm = txt.match(jiymatcher); + if (mm) { + var mmx = []; + for (pos = 0, len = mm.length; pos < len; pos += 1) { + mmx = mmx.concat(mm[pos].match(/([^0-9]+)([0-9]+)/).slice(1)); } - ret[i + 1].UGLY_DELIMITER_SUPPRESS_HACK = true; + for (pos = 0, len = slst.length; pos < len; pos += 1) { + lst.push(slst[pos]); + if (pos !== (len - 1)) { + mmpos = (pos * 2); + lst.push(mmx[mmpos]); + lst.push(mmx[mmpos + 1]); + } + } + } else { + lst = slst; + } + l = lst.length; + for (pos = 1; pos < l; pos += 3) { + lst[pos + 1] = jiy[lst[pos]] + parseInt(lst[pos + 1], 10); + lst[pos] = ""; } + txt = lst.join(""); + txt = txt.replace(/\s*-\s*$/, "").replace(/\s*-\s*\//, "/"); + txt = txt.replace(/\.\s*$/, ""); + txt = txt.replace(/\.(?! )/, ""); + slash = txt.indexOf("/"); + dash = txt.indexOf("-"); } } - if (blob && (blob.decorations.length || blob.strings.suffix || blob.strings.prefix)) { - span_split = ret.length; - } - var blobs_start = state.output.renderBlobs(ret.slice(0, span_split), blob_delimiter, true); - if (blobs_start && blob && (blob.decorations.length || blob.strings.suffix || blob.strings.prefix)) { - if (!state.tmp.suppress_decorations) { - for (i = 0, ilen = blob.decorations.length; i < ilen; i += 1) { - params = blob.decorations[i]; - if (["@cite","@bibliography", "@display", "@showid"].indexOf(params[0]) > -1) { + txt = txt.replace(/([A-Za-z])\./g, "$1"); + number = ""; + note = ""; + thedate = {}; + if (txt.slice(0, 1) === "\"" && txt.slice(-1) === "\"") { + thedate.literal = txt.slice(1, -1); + return thedate; + } + if (slash > -1 && dash > -1) { + slashcount = txt.split("/"); + if (slashcount.length > 3) { + range_delim = "-"; + date_delim = "/"; + lst = txt.split(rexslashdash); + } else { + range_delim = "/"; + date_delim = "-"; + lst = txt.split(rexdashslash); + } + } else { + txt = txt.replace("/", "-"); + range_delim = "-"; + date_delim = "-"; + lst = txt.split(rexdash); + } + ret = []; + len = lst.length; + for (pos = 0; pos < len; pos += 1) { + item = lst[pos]; + m = item.match(/^\s*([\-\/]|[a-zA-Z]+|[\-~?0-9]+)\s*$/); + if (m) { + ret.push(m[1]); + } + } + delim_pos = ret.indexOf(range_delim); + delims = []; + isrange = false; + if (delim_pos > -1) { + delims.push([0, delim_pos]); + delims.push([(delim_pos + 1), ret.length]); + isrange = true; + } else { + delims.push([0, ret.length]); + } + suff = ""; + for (i = 0, ilen = delims.length; i < ilen; i += 1) { + delim = delims[i]; + date = ret.slice(delim[0], delim[1]); + for (j = 0, jlen = date.length; j < jlen; j += 1) { + element = date[j]; + if (element.indexOf(date_delim) > -1) { + this.parseNumericDate(thedate, date_delim, suff, element); continue; } - if (state.normalDecorIsOrphan(blobjr, params)) { + if (element.match(/[0-9]{4}/)) { + thedate[("year" + suff)] = element.replace(/^0*/, ""); + continue; + } + breakme = false; + for (k = 0, klen = this.mrexes.length; k < klen; k += 1) { + if (element.toLocaleLowerCase().match(this.mrexes[k])) { + thedate[("month" + suff)] = "" + (parseInt(k, 10) + 1); + breakme = true; + break; + } + if (breakme) { + continue; + } + if (element.match(/^[0-9]+$/)) { + number = parseInt(element, 10); + } + if (element.toLocaleLowerCase().match(/^bc/) && number) { + thedate[("year" + suff)] = "" + (number * -1); + number = ""; + continue; + } + if (element.toLocaleLowerCase().match(/^ad/) && number) { + thedate[("year" + suff)] = "" + number; + number = ""; + continue; + } + } + breakme = false; + for (k = 0, klen = seasonrexes.length; k < klen; k += 1) { + if (element.toLocaleLowerCase().match(seasonrexes[k])) { + thedate[("season" + suff)] = "" + (parseInt(k, 10) + 1); + breakme = true; + break; + } + } + if (breakme) { + continue; + } + if (element === "~" || element === "?" || element === "c" || element.match(/^cir/)) { + thedate.circa = "" + 1; + continue; + } + if (element.toLocaleLowerCase().match(/(?:mic|tri|hil|eas)/) && !thedate[("season" + suff)]) { + note = element; continue; } - blobs_start = state.fun.decorate[params[0]][params[1]](state, blobs_start, params[2]); } - } - b = blobs_start; - use_suffix = blob.strings.suffix; - if (b && b.length) { - use_prefix = blob.strings.prefix; - b = txt_esc(use_prefix, state.tmp.nestedBraces) + b + txt_esc(use_suffix, state.tmp.nestedBraces); - if (state.tmp.count_offset_characters) { - state.tmp.offset_characters += (use_prefix.length + use_suffix.length); + if (number) { + thedate[("day" + suff)] = number; + number = ""; } + if (note && !thedate[("season" + suff)]) { + thedate[("season" + suff)] = note; + note = ""; + } + suff = "_end"; } - blobs_start = b; - if (!state.tmp.suppress_decorations) { - for (i = 0, ilen = blob.decorations.length; i < ilen; i += 1) { - params = blob.decorations[i]; - if (["@cite","@bibliography", "@display", "@showid"].indexOf(params[0]) === -1) { - continue; + if (isrange) { + for (j = 0, jlen = CSL.DATE_PARTS_ALL.length; j < jlen; j += 1) { + item = CSL.DATE_PARTS_ALL[j]; + if (thedate[item] && !thedate[(item + "_end")]) { + thedate[(item + "_end")] = thedate[item]; + } else if (!thedate[item] && thedate[(item + "_end")]) { + thedate[item] = thedate[(item + "_end")]; } - blobs_start = state.fun.decorate[params[0]][params[1]].call(blob, state, blobs_start, params[2]); } } - } - var blobs_end = ret.slice(span_split, ret.length); - if (!blobs_end.length && blobs_start) { - ret = [blobs_start]; - } else if (blobs_end.length && !blobs_start) { - ret = blobs_end; - } else if (blobs_start && blobs_end.length) { - ret = [blobs_start].concat(blobs_end); - } - if ("undefined" === typeof blob) { - this.queue = []; - this.current.mystack = []; - this.current.mystack.push(this.queue); - if (state.tmp.suppress_decorations) { - ret = state.output.renderBlobs(ret, undefined, true); + if (!thedate.year) { + thedate = { "literal": txt }; } - } else if ("boolean" === typeof blob) { - ret = state.output.renderBlobs(ret, undefined, true); - } - if (blob && blob.new_locale) { - state.opt.lang = blob.old_locale; - } - return ret; -}; -CSL.Output.Queue.prototype.clearlevel = function () { - var blob, pos, len; - blob = this.current.value(); - len = blob.blobs.length; - for (pos = 0; pos < len; pos += 1) { - blob.blobs.pop(); - } -}; -CSL.Output.Queue.prototype.renderBlobs = function (blobs, delim, in_cite) { - var state, ret, ret_last_char, use_delim, i, blob, pos, len, ppos, llen, pppos, lllen, res, str, params, txt_esc; - txt_esc = CSL.getSafeEscape(this.state); - if (!delim) { - delim = ""; - } - state = this.state; - ret = ""; - ret_last_char = []; - use_delim = ""; - len = blobs.length; - var start = true; - for (pos = 0; pos < len; pos += 1) { - if (blobs[pos].checkNext) { - blobs[pos].checkNext(blobs[(pos + 1)],start); - start = false; - } else { - start = true; - } - } - var doit = true; - for (pos = blobs.length - 1; pos > 0; pos += -1) { - if (blobs[pos].checkLast) { - if (doit && blobs[pos].checkLast(blobs[pos - 1])) { - doit = false; - } - } else { - doit = true; - } - } - len = blobs.length; - for (pos = 0; pos < len; pos += 1) { - blob = blobs[pos]; - if (ret) { - use_delim = delim; + if (this.use_array) { + this.toArray(thedate); } - if (blob && "string" === typeof blob) { - ret += txt_esc(use_delim); - ret += blob; - if (state.tmp.count_offset_characters) { - state.tmp.offset_characters += (use_delim.length); - } - } else if (blob.status !== CSL.SUPPRESS) { - str = blob.formatter.format(blob.num, blob.gender); - var strlen = str.replace(/<[^>]*>/g, "").length; - this.append(str, "empty", true); - var str_blob = this.pop(); - var count_offset_characters = state.tmp.count_offset_characters; - str = this.string(state, [str_blob], false); - state.tmp.count_offset_characters = count_offset_characters; - if (blob.strings["text-case"]) { - str = CSL.Output.Formatters[blob.strings["text-case"]](this.state, str); + return thedate; + }; + this.returnAsArray = function () { + this.use_array = true; + }; + this.returnAsKeys = function () { + this.use_array = false; + }; + this.toArray = function (thedate) { + var i, ilen, part; + thedate["date-parts"] = []; + thedate["date-parts"].push([]); + var slicelen = 0; + for (i = 0, ilen = 3; i < ilen; i += 1) { + part = ["year", "month", "day"][i]; + if (!thedate[part]) { + break; } - if (str && this.state.tmp.strip_periods) { - str = str.replace(/\.([^a-z]|$)/g, "$1"); + slicelen += 1; + thedate["date-parts"][0].push(thedate[part]); + delete thedate[part]; + } + for (i = 0, ilen = slicelen; i < ilen; i += 1) { + part = ["year_end", "month_end", "day_end"][i]; + if (thedate[part] && thedate["date-parts"].length === 1) { + thedate["date-parts"].push([]); } - if (!state.tmp.suppress_decorations) { - llen = blob.decorations.length; - for (ppos = 0; ppos < llen; ppos += 1) { - params = blob.decorations[ppos]; - if (state.normalDecorIsOrphan(blob, params)) { - continue; - } - str = state.fun.decorate[params[0]][params[1]](state, str, params[2]); + thedate["date-parts"][1].push(thedate[part]); + delete thedate[part]; + } + }; + this.parseNumericDate = function (ret, delim, suff, txt) { + var lst, i, ilen; + lst = txt.split(delim); + for (i = 0, ilen = lst.length; i < ilen; i += 1) { + if (lst[i].length === 4) { + ret[("year" + suff)] = lst[i].replace(/^0*/, ""); + if (!i) { + lst = lst.slice(1); + } else { + lst = lst.slice(0, i); } + break; } - str = txt_esc(blob.strings.prefix) + str + txt_esc(blob.strings.suffix); - var addme = ""; - if (blob.status === CSL.END) { - addme = txt_esc(blob.range_prefix); - } else if (blob.status === CSL.SUCCESSOR) { - addme = txt_esc(blob.successor_prefix); - } else if (blob.status === CSL.START) { - addme = ""; - } else if (blob.status === CSL.SEEN) { - addme = txt_esc(blob.splice_prefix); - } - ret += addme; - ret += str; - if (state.tmp.count_offset_characters) { - state.tmp.offset_characters += (addme.length + blob.strings.prefix.length + strlen + blob.strings.suffix.length); + } + for (i = 0, ilen = lst.length; i < ilen; i += 1) { + lst[i] = parseInt(lst[i], 10); + } + if (lst.length === 1 || (lst.length === 2 && !lst[1])) { + ret[("month" + suff)] = "" + lst[0]; + } else if (lst.length === 2) { + if (lst[this.monthguess] > 12) { + ret[("month" + suff)] = "" + lst[this.dayguess]; + ret[("day" + suff)] = "" + lst[this.monthguess]; + } else { + ret[("month" + suff)] = "" + lst[this.monthguess]; + ret[("day" + suff)] = "" + lst[this.dayguess]; } } - } - return ret; + }; }; -CSL.Output.Queue.purgeEmptyBlobs = function (myblobs, endOnly) { - var res, i, ilen, j, jlen, tmpblobs; - if ("string" === typeof myblobs || !myblobs.length) { - return; +CSL.Engine = function (sys, style, lang, forceLang) { + var attrs, langspec, localexml, locale; + this.processor_version = CSL.PROCESSOR_VERSION; + this.csl_version = "1.0"; + this.sys = sys; + this.sys.xml = new CSL.System.Xml.Parsing(); + if ("undefined" === typeof CSL_JSON && "string" !== typeof style) { + style = ""; } - for (i = myblobs.length - 1; i > -1; i += -1) { - CSL.Output.Queue.purgeEmptyBlobs(myblobs[i].blobs, endOnly); + if (CSL.getAbbreviation) { + this.sys.getAbbreviation = CSL.getAbbreviation; } - for (i = myblobs.length - 1; i > -1; i += -1) { - if (!myblobs[i].blobs.length) { - tmpblobs = myblobs.slice(i + 1); - for (j = i, jlen = myblobs.length; j < jlen; j += 1) { - myblobs.pop(); - } - for (j = 0, jlen = tmpblobs.length; j < jlen; j += 1) { - myblobs.push(tmpblobs[j]); + if (this.sys.stringCompare) { + CSL.stringCompare = this.sys.stringCompare; + } + this.sys.AbbreviationSegments = CSL.AbbreviationSegments; + this.parallel = new CSL.Parallel(this); + this.transform = new CSL.Transform(this); + this.setParseNames = function (val) { + this.opt['parse-names'] = val; + }; + this.opt = new CSL.Engine.Opt(); + this.tmp = new CSL.Engine.Tmp(); + this.build = new CSL.Engine.Build(); + this.fun = new CSL.Engine.Fun(this); + this.configure = new CSL.Engine.Configure(); + this.citation_sort = new CSL.Engine.CitationSort(); + this.bibliography_sort = new CSL.Engine.BibliographySort(); + this.citation = new CSL.Engine.Citation(this); + this.bibliography = new CSL.Engine.Bibliography(); + this.output = new CSL.Output.Queue(this); + this.dateput = new CSL.Output.Queue(this); + this.cslXml = this.sys.xml.makeXml(style); + if (this.opt.development_extensions.csl_reverse_lookup_support) { + this.build.cslNodeId = 0; + this.setCslNodeIds = function(myxml, nodename) { + var children = this.sys.xml.children(myxml); + this.sys.xml.setAttribute(myxml, 'cslid', this.build.cslNodeId); + this.opt.nodenames.push(nodename); + this.build.cslNodeId += 1; + for (var i = 0, ilen = this.sys.xml.numberofnodes(children); i < ilen; i += 1) { + nodename = this.sys.xml.nodename(children[i]); + if (nodename) { + this.setCslNodeIds(children[i], nodename); + } } - } - if (endOnly) { - break; - } + }; + this.setCslNodeIds(this.cslXml, "style"); } -}; -CSL.Output.Queue.purgeNearsidePrefixChars = function(myblob, chr) { - if (!chr) { - return; + this.sys.xml.addMissingNameNodes(this.cslXml); + this.sys.xml.addInstitutionNodes(this.cslXml); + this.sys.xml.insertPublisherAndPlace(this.cslXml); + this.sys.xml.flagDateMacros(this.cslXml); + attrs = this.sys.xml.attributes(this.cslXml); + if ("undefined" === typeof attrs["@sort-separator"]) { + this.sys.xml.setAttribute(this.cslXml, "sort-separator", ", "); } - if ("object" === typeof myblob) { - if ((CSL.TERMINAL_PUNCTUATION.indexOf(chr) > -1 - && CSL.TERMINAL_PUNCTUATION.slice(0, -1).indexOf(myblob.strings.prefix.slice(0, 1)) > -1) - && !(myblob.strings.prefix.slice(0,1) === ";" && chr === ".")) { - myblob.strings.prefix = myblob.strings.prefix.slice(1); - } else if ("object" === typeof myblob.blobs) { - CSL.Output.Queue.purgeNearsidePrefixChars(myblob.blobs[0], chr); - } + this.opt["initialize-with-hyphen"] = true; + this.setStyleAttributes(); + this.opt.xclass = sys.xml.getAttributeValue(this.cslXml, "class"); + this.opt.styleID = this.sys.xml.getStyleId(this.cslXml); + if (lang) { + lang = lang.replace("_", "-"); } -}; -CSL.Output.Queue.purgeNearsidePrefixSpaces = function(myblob, chr) { - if ("object" === typeof myblob) { - if (" " === chr && " " === myblob.strings.prefix.slice(0, 1)) { - myblob.strings.prefix = myblob.strings.prefix.slice(1); - } else if ("object" === typeof myblob.blobs) { - CSL.Output.Queue.purgeNearsidePrefixSpaces(myblob.blobs[0], chr); - } + if (this.opt["default-locale"][0]) { + this.opt["default-locale"][0] = this.opt["default-locale"][0].replace("_", "-"); } -}; -CSL.Output.Queue.purgeNearsideSuffixSpaces = function(myblob, chr) { - if ("object" === typeof myblob) { - if (" " === chr && " " === myblob.strings.suffix.slice(-1)) { - myblob.strings.suffix = myblob.strings.suffix.slice(0, -1); - } else if ("object" === typeof myblob.blobs) { - if (!chr) { - chr = myblob.strings.suffix.slice(-1); - } - chr = CSL.Output.Queue.purgeNearsideSuffixSpaces(myblob.blobs[myblob.blobs.length - 1], chr); - } else { - chr = myblob.strings.suffix.slice(-1); + if (lang && forceLang) { + this.opt["default-locale"] = [lang]; + } + if (lang && !forceLang && this.opt["default-locale"][0]) { + lang = this.opt["default-locale"][0]; + } + if (this.opt["default-locale"].length === 0) { + if (!lang) { + lang = "en-US"; } + this.opt["default-locale"].push("en-US"); } - return chr; -}; -CSL.Output.Queue.adjustPunctuation = function (state, myblobs, stk) { - var chr, suffix, dpref, blob, delimiter, suffixX, dprefX, blobX, delimiterX, prefix, prefixX, dsuffX, dsuff, slast, dsufff, dsufffX, lastchr, firstchr, exposed_suffixes, exposed, j, jlen, i, ilen; - var TERMS = CSL.TERMINAL_PUNCTUATION.slice(0, -1); - var TERM_OR_SPACE = CSL.TERMINAL_PUNCTUATION; - var SWAPS = CSL.SWAPPING_PUNCTUATION; - if (!stk) { - stk = [{suffix: "", delimiter: "", lastNode:true}]; + if (!lang) { + lang = this.opt["default-locale"][0]; } - slast = stk.length - 1; - delimiter = stk[slast].delimiter; - dpref = stk[slast].dpref; - dsuff = stk[slast].dsuff; - dsufff = stk[slast].dsufff; - prefix = stk[slast].prefix; - suffix = stk[slast].suffix; - blob = stk[slast].blob; - if ("string" === typeof myblobs) { - if (suffix) { - if (blob && - TERMS.indexOf(myblobs.slice(-1)) > -1 && - TERMS.slice(1).indexOf(suffix) > -1 && - blob.strings.suffix !== " ") { - blob.strings.suffix = blob.strings.suffix.slice(1); - } + langspec = CSL.localeResolve(lang); + this.opt.lang = langspec.best; + this.opt["default-locale"][0] = langspec.best; + this.locale = {}; + this.localeConfigure(langspec); + this.registry = new CSL.Registry(this); + this.buildTokenLists("citation"); + this.buildTokenLists("bibliography"); + this.configureTokenLists(); + this.disambiguate = new CSL.Disambiguation(this); + this.splice_delimiter = false; + this.fun.dateparser = new CSL.DateParser(); + this.fun.flipflopper = new CSL.Util.FlipFlopper(this); + this.setCloseQuotesArray(); + this.fun.ordinalizer.init(this); + this.fun.long_ordinalizer.init(this); + this.fun.page_mangler = CSL.Util.PageRangeMangler.getFunction(this, "page"); + this.fun.year_mangler = CSL.Util.PageRangeMangler.getFunction(this, "year"); + this.setOutputFormat("html"); +}; +CSL.Engine.prototype.setCloseQuotesArray = function () { + var ret; + ret = []; + ret.push(this.getTerm("close-quote")); + ret.push(this.getTerm("close-inner-quote")); + ret.push('"'); + ret.push("'"); + this.opt.close_quotes_array = ret; +}; +CSL.Engine.prototype.buildTokenLists = function (area) { + var area_nodes, navi; + area_nodes = this.sys.xml.getNodesByName(this.cslXml, area); + if (!this.sys.xml.getNodeValue(area_nodes)) { + return; + } + navi = new this.getNavi(this, area_nodes); + this.build.area = area; + CSL.buildStyle.call(this, navi); +}; +CSL.Engine.prototype.setStyleAttributes = function () { + var dummy, attr, key, attributes, attrname; + dummy = {}; + dummy.name = this.sys.xml.nodename(this.cslXml); + attributes = this.sys.xml.attributes(this.cslXml); + for (attrname in attributes) { + if (attributes.hasOwnProperty(attrname)) { + CSL.Attributes[attrname].call(dummy, this, attributes[attrname]); } - lastchr = myblobs.slice(-1); - firstchr = myblobs.slice(0,1); + } +}; +CSL.buildStyle = function (navi) { + if (navi.getkids()) { + CSL.buildStyle.call(this, navi); } else { - if (dpref) { - for (j = 0, jlen = myblobs.length - 1; j < jlen; j += 1) { - var t = myblobs[j].strings.suffix.slice(-1); - if (TERMS.indexOf(t) === -1 || - TERMS.indexOf(dpref) === -1) { - if (dpref !== " " || dpref !== myblobs[j].strings.suffix.slice(-1)) { - myblobs[j].strings.suffix += dpref; - } + if (navi.getbro()) { + CSL.buildStyle.call(this, navi); + } else { + while (navi.nodeList.length > 1) { + if (navi.remember()) { + CSL.buildStyle.call(this, navi); } } } - if (suffix === " ") { - CSL.Output.Queue.purgeNearsideSuffixSpaces(myblobs[myblobs.length - 1], " "); + } +}; +CSL.Engine.prototype.getNavi = function (state, myxml) { + this.sys = state.sys; + this.state = state; + this.nodeList = []; + this.nodeList.push([0, myxml]); + this.depth = 0; +}; +CSL.Engine.prototype.getNavi.prototype.remember = function () { + var node; + this.depth += -1; + this.nodeList.pop(); + node = this.nodeList[this.depth][1][(this.nodeList[this.depth][0])]; + CSL.XmlToToken.call(node, this.state, CSL.END); + return this.getbro(); +}; +CSL.Engine.prototype.getNavi.prototype.getbro = function () { + var sneakpeek; + sneakpeek = this.nodeList[this.depth][1][(this.nodeList[this.depth][0] + 1)]; + if (sneakpeek) { + this.nodeList[this.depth][0] += 1; + return true; + } else { + return false; + } +}; +CSL.Engine.prototype.getNavi.prototype.getkids = function () { + var currnode, sneakpeek, pos, node, len; + currnode = this.nodeList[this.depth][1][this.nodeList[this.depth][0]]; + sneakpeek = this.sys.xml.children(currnode); + if (this.sys.xml.numberofnodes(sneakpeek) === 0) { + if (this.depth) { + CSL.XmlToToken.call(currnode, this.state, CSL.SINGLETON); } - var lst = []; - var doblob; - for (i = 0, ilen = myblobs.length - 1; i < ilen; i += 1) { - doblob = myblobs[i]; - var following_prefix = myblobs[i + 1].strings.prefix; - chr = false; - var ret = CSL.Output.Queue.purgeNearsideSuffixSpaces(doblob, chr); - if (!dsuff) { - lst.push(ret); - } else { - lst.push(false); + return false; + } else { + for (pos in sneakpeek) { + node = sneakpeek[pos]; + if ("date" === this.sys.xml.nodename(node)) { + currnode = CSL.Util.fixDateNode.call(this, currnode, pos, node); + sneakpeek = this.sys.xml.children(currnode); } } - chr = false; - for (i = 1, ilen = myblobs.length; i < ilen; i += 1) { - doblob = myblobs[i]; - chr = ""; - var preceding_suffix = myblobs[i - 1].strings.suffix; - if (dsuff === " ") { - chr = dsuff; - } else if (preceding_suffix) { - chr = preceding_suffix.slice(-1); - } else if (lst[i - 1]) { - chr = lst[i - 1]; - } - CSL.Output.Queue.purgeNearsidePrefixSpaces(doblob, chr); + CSL.XmlToToken.call(currnode, this.state, CSL.START); + this.depth += 1; + this.nodeList.push([0, sneakpeek]); + return true; + } +}; +CSL.Engine.prototype.getNavi.prototype.getNodeListValue = function () { + return this.nodeList[this.depth][1]; +}; +CSL.Engine.prototype.getTerm = function (term, form, plural, gender, mode, forceDefaultLocale) { + if (term && term.match(/[A-Z]/) && term === term.toUpperCase()) { + CSL.debug("Warning: term key is in uppercase form: "+term); + term = term.toLowerCase(); + } + var lang; + if (forceDefaultLocale) { + lang = this.opt["default-locale"][0]; + } else { + lang = this.opt.lang; + } + var ret = CSL.Engine.getField(CSL.LOOSE, this.locale[lang].terms, term, form, plural, gender); + if (!ret && term === "range-delimiter") { + ret = "\u2013"; + } + if (typeof ret === "undefined") { + if (mode === CSL.STRICT) { + throw "Error in getTerm: term \"" + term + "\" does not exist."; + } else if (mode === CSL.TOLERANT) { + ret = ""; } - if (dsufff) { - CSL.Output.Queue.purgeNearsidePrefixSpaces(myblobs[0], " "); - } else if (prefix === " ") { - CSL.Output.Queue.purgeNearsidePrefixSpaces(myblobs[0], " "); + } + if (ret) { + this.tmp.cite_renders_content = true; + } + return ret; +}; +CSL.Engine.prototype.getDate = function (form, forceDefaultLocale) { + var lang; + if (forceDefaultLocale) { + lang = this.opt["default-locale"]; + } else { + lang = this.opt.lang; + } + if (this.locale[lang].dates[form]) { + return this.locale[lang].dates[form]; + } else { + return false; + } +}; +CSL.Engine.prototype.getOpt = function (arg) { + if ("undefined" !== typeof this.locale[this.opt.lang].opts[arg]) { + return this.locale[this.opt.lang].opts[arg]; + } else { + return false; + } +}; +CSL.Engine.prototype.getVariable = function (Item, varname, form, plural) { + return CSL.Engine.getField(CSL.LOOSE, Item, varname, form, plural); +}; +CSL.Engine.prototype.getDateNum = function (ItemField, partname) { + if ("undefined" === typeof ItemField) { + return 0; + } else { + return ItemField[partname]; + } +}; +CSL.Engine.getField = function (mode, hash, term, form, plural, gender) { + var ret, forms, f, pos, len, hashterm; + ret = ""; + if ("undefined" === typeof hash[term]) { + if (mode === CSL.STRICT) { + throw "Error in getField: term \"" + term + "\" does not exist."; + } else { + return undefined; } - for (i = 0, ilen = myblobs.length; i < ilen; i += 1) { - doblob = myblobs[i]; - CSL.Output.Queue.purgeNearsidePrefixChars(doblob, lastchr); - if (i === 0) { - if (prefix) { - if (doblob.strings.prefix.slice(0, 1) === " ") { - } - } - } - if (dsufff) { - if (doblob.strings.prefix) { - if (i === 0) { - if (doblob.strings.prefix.slice(0, 1) === " ") { - } - } - } - } - if (dsuff) { - if (i > 0) { - if (doblob.strings.prefix.slice(0, 1) === " ") { - } - } - } - if (i < (myblobs.length - 1)) { - var nextprefix = myblobs[i + 1].strings.prefix; - if (!delimiter) { - if (nextprefix) { - var nxtchr = nextprefix.slice(0, 1); - if (SWAPS.indexOf(nxtchr) > -1) { - myblobs[i + 1].strings.prefix = nextprefix.slice(1); - if (TERMS.indexOf(nxtchr) === -1 || - (TERMS.indexOf(nxtchr) > -1 && - TERMS.indexOf(doblob.strings.suffix.slice(-1)) === -1)) { - doblob.strings.suffix += nxtchr; - } - } else if (nxtchr === " " && - doblob.strings.suffix.slice(-1) === " ") { - doblob.strings.suffix = doblob.strings.suffix.slice(0, -1); - } - } + } + if (gender && hash[term][gender]) { + hashterm = hash[term][gender]; + } else { + hashterm = hash[term]; + } + forms = []; + if (form === "symbol") { + forms = ["symbol", "short"]; + } else if (form === "verb-short") { + forms = ["verb-short", "verb"]; + } else if (form !== "long") { + forms = [form]; + } + forms = forms.concat(["long"]); + len = forms.length; + for (pos = 0; pos < len; pos += 1) { + f = forms[pos]; + if ("string" === typeof hashterm || "number" === typeof hashterm) { + ret = hashterm; + } else if ("undefined" !== typeof hashterm[f]) { + if ("string" === typeof hashterm[f] || "number" === typeof hashterm[f]) { + ret = hashterm[f]; + } else { + if ("number" === typeof plural) { + ret = hashterm[f][plural]; + } else { + ret = hashterm[f][0]; } } - if (i === (myblobs.length - 1)) { - if (suffix) { - if (doblob.strings.suffix && - (TERMS.slice(1).indexOf(suffix) > -1 && - TERMS.indexOf(doblob.strings.suffix.slice(-1)) > -1)) { - blob.strings.suffix = blob.strings.suffix.slice(1); + break; + } + } + return ret; +}; +CSL.Engine.prototype.configureTokenLists = function () { + var dateparts_master, area, pos, token, dateparts, part, ppos, pppos, len, llen, lllen; + dateparts_master = ["year", "month", "day"]; + len = CSL.AREAS.length; + for (pos = 0; pos < len; pos += 1) { + area = CSL.AREAS[pos]; + llen = this[area].tokens.length - 1; + for (ppos = llen; ppos > -1; ppos += -1) { + token = this[area].tokens[ppos]; + if ("date" === token.name && CSL.END === token.tokentype) { + dateparts = []; + } + if ("date-part" === token.name && token.strings.name) { + lllen = dateparts_master.length; + for (pppos = 0; pppos < lllen; pppos += 1) { + part = dateparts_master[pppos]; + if (part === token.strings.name) { + dateparts.push(token.strings.name); } } } - if (state.getOpt('punctuation-in-quote')) { - var decorations = doblob.decorations; - for (j = 0, jlen = decorations.length; j < jlen; j += 1) { - if (decorations[j][0] === '@quotes' && decorations[j][1] === 'true') { - doblob.punctuation_in_quote = true; - stk[slast].lastNode = true; + if ("date" === token.name && CSL.START === token.tokentype) { + dateparts.reverse(); + token.dateparts = dateparts; + } + token.next = (ppos + 1); + if (token.name && CSL.Node[token.name].configure) { + CSL.Node[token.name].configure.call(token, this, ppos); + } + } + } + this.version = CSL.version; + return this.state; +}; +CSL.Engine.prototype.retrieveItems = function (ids) { + var ret, pos, len; + ret = []; + for (var i = 0, ilen = ids.length; i < ilen; i += 1) { + ret.push(this.retrieveItem("" + ids[i])); + } + return ret; +}; +CSL.ITERATION = 0; +CSL.Engine.prototype.retrieveItem = function (id) { + var Item, m, pos, len, mm; + if (this.opt.development_extensions.normalize_lang_keys_to_lowercase && + "boolean" === typeof this.opt.development_extensions.normalize_lang_keys_to_lowercase) { + for (var i=0,ilen=this.opt["default-locale"].length; i<ilen; i+=1) { + this.opt["default-locale"][i] = this.opt["default-locale"][i].toLowerCase(); + } + for (var i=0,ilen=this.opt["locale-translit"].length; i<ilen; i+=1) { + this.opt["locale-translit"][i] = this.opt["locale-translit"][i].toLowerCase(); + } + for (var i=0,ilen=this.opt["locale-translat"].length; i<ilen; i+=1) { + this.opt["locale-translat"][i] = this.opt["locale-translat"][i].toLowerCase(); + } + this.opt.development_extensions.normalize_lang_keys_to_lowercase = 100; + } + CSL.ITERATION += 1; + Item = this.sys.retrieveItem("" + id); + if (this.opt.development_extensions.normalize_lang_keys_to_lowercase) { + if (Item.multi) { + if (Item.multi._keys) { + for (var field in Item.multi._keys) { + for (var key in Item.multi._keys[field]) { + if (key !== key.toLowerCase()) { + Item.multi._keys[field][key.toLowerCase()] = Item.multi._keys[field][key]; + delete Item.multi._keys[field][key]; + } } } } - if (doblob.punctuation_in_quote && stk[slast].lastNode) { - var swapchar = doblob.strings.suffix.slice(0, 1); - var swapblob = false; - if (SWAPS.indexOf(swapchar) > -1) { - swapblob = doblob; - } else if (SWAPS.indexOf(suffix) > -1 && i === (myblobs.length - 1)) { - swapchar = suffix; - swapblob = blob; - } else { - swapchar = false; + if (Item.multi.main) { + for (var field in Item.multi.main) { + Item.multi.main[field] = Item.multi.main[field].toLowerCase(); } - if (swapchar) { - if ("string" === typeof doblob.blobs) { - if (SWAPS.indexOf(doblob.blobs.slice(-1)) === -1 || - (TERMS.indexOf(doblob.blobs.slice(-1)) > -1 && - SWAPS.indexOf(swapchar) > -1 && - TERMS.indexOf(swapchar) === -1)) { - doblob.blobs += swapchar; + } + } + for (var i=0, ilen=CSL.CREATORS.length; i>ilen; i+=1) { + var ctype = CSL.CREATORS[i]; + if (Item[ctype] && Item[ctype].multi) { + for (var j=0, jlen=Item[ctype].length; j<jlen; j+=1) { + var creator = Item[ctype][j]; + if (creator.multi) { + if (creator.multi._key) { + for (var key in creator.multi._key) { + if (key !== key.toLowerCase()) { + creator.multi._key[key.toLowerCase()] = creator.multi._key[key]; + delete creator.multi._key[key]; + } + } } - } else { - if (SWAPS.indexOf(doblob.blobs.slice(-1)[0].strings.suffix.slice(-1)) === -1 || - (TERMS.indexOf(doblob.blobs.slice(-1)[0].strings.suffix.slice(-1)) > -1 && - SWAPS.indexOf(swapchar) > -1 && - TERMS.indexOf(swapchar) === -1)) { - doblob.blobs.slice(-1)[0].strings.suffix += swapchar; + if (creator.multi.main) { + creator.multi.main = creator.multi.main.toLowerCase(); } } - swapblob.strings.suffix = swapblob.strings.suffix.slice(1); } } - if (i === (myblobs.length - 1)) { - if (doblob.strings.suffix) { - suffixX = doblob.strings.suffix.slice(0, 1); - blobX = doblob; - } else { - suffixX = stk[stk.length - 1].suffix; - blobX = stk[stk.length - 1].blob; - } - } else { - if (doblob.strings.suffix) { - suffixX = doblob.strings.suffix.slice(0, 1); - blobX = doblob; - } else { - suffixX = ""; - blobX = false; + } + } + if (Item.page) { + Item["page-first"] = Item.page; + var num = "" + Item.page; + m = num.split(/\s*(?:&|,|-|\u2013)\s*/); + if (m[0].slice(-1) !== "\\") { + Item["page-first"] = m[0]; + } + } + if (this.opt.development_extensions.field_hack && Item.note) { + m = Item.note.match(CSL.NOTE_FIELDS_REGEXP); + if (m) { + var names = {}; + for (pos = 0, len = m.length; pos < len; pos += 1) { + mm = m[pos].match(CSL.NOTE_FIELD_REGEXP); + if (!Item[mm[1]] && CSL.DATE_VARIABLES.indexOf(mm[1]) > -1) { + Item[mm[1]] = {raw:mm[2]}; + } else if (!Item[mm[1]] && CSL.NAME_VARIABLES.indexOf(mm[1]) > -1) { + if (!Item[mm[1]]) { + Item[mm[1]] = []; + } + var lst = mm[2].split(/\s*\|\|\s*/); + if (lst.length === 1) { + Item[mm[1]].push({family:lst[0],isInstitution:true}); + } else if (lst.length === 2) { + Item[mm[1]].push({family:lst[0],given:lst[1]}); + } + } else if (!Item[mm[1]] || mm[1] === "type") { + Item[mm[1]] = mm[2].replace(/^\s+/, "").replace(/\s+$/, ""); } + Item.note.replace(CSL.NOTE_FIELD_REGEXP, ""); } - if (SWAPS.concat([" "]).indexOf(suffixX) === -1) { - suffixX = ""; - blobX = false; - } - if (doblob.strings.delimiter && - doblob.blobs.length > 1) { - dprefX = doblob.strings.delimiter.slice(0, 1); - if (SWAPS.concat([" "]).indexOf(dprefX) > -1) { - doblob.strings.delimiter = doblob.strings.delimiter.slice(1); - } else { - dprefX = ""; + } + } + for (var i = 1, ilen = CSL.DATE_VARIABLES.length; i < ilen; i += 1) { + var dateobj = Item[CSL.DATE_VARIABLES[i]]; + if (dateobj) { + if (this.opt.development_extensions.raw_date_parsing) { + if (dateobj.raw) { + dateobj = this.fun.dateparser.parse(dateobj.raw); } - } else { - dprefX = ""; } - if (doblob.strings.prefix) { - if (doblob.strings.prefix.slice(-1) === " ") { - prefixX = " "; - } else { - prefixX = ""; - } - } else { - if (i === 0) { - prefixX = prefix; - } else { - prefixX = ""; + Item[CSL.DATE_VARIABLES[i]] = this.dateParseArray(dateobj); + } + } + if (this.opt.development_extensions.static_statute_locator) { + if (Item.type && ["bill","gazette","legislation","treaty"].indexOf(Item.type) > -1) { + var varname; + var elements = ["type", "title", "jurisdiction", "genre", "volume", "container-title"]; + var legislation_id = []; + for (i = 0, ilen = elements.length; i < ilen; i += 1) { + varname = elements[i]; + if (Item[varname]) { + legislation_id.push(Item[varname]); } } - if (dsuff) { - dsufffX = dsuff; - } else { - if (i === 0) { - dsufffX = dsufff; - } else { - dsufffX = ""; - } - } - if (doblob.strings.delimiter) { - if (doblob.strings.delimiter.slice(-1) === " " && - "object" === typeof doblob.blobs && doblob.blobs.length > 1) { - dsuffX = doblob.strings.delimiter.slice(-1); - } else { - dsuffX = ""; + elements = ["original-date", "issued"]; + for (i = 0, elements.length; i < ilen; i += 1) { + varname = elements[i]; + if (Item[varname] && Item[varname].year) { + var value = Item[varname].year; + legislation_id.push(value); + break; } - } else { - dsuffX = ""; - } - delimiterX = doblob.strings.delimiter; - var lastNode - if (i === (myblobs.length - 1) && stk[slast].lastNode) { - lastNode = true; - } else { - lastNode = false; } - stk.push({suffix: suffixX, dsuff:dsuffX, blob:blobX, delimiter:delimiterX, prefix:prefixX, dpref: dprefX, dsufff: dsufffX, lastNode: lastNode}); - lastchr = CSL.Output.Queue.adjustPunctuation(state, doblob.blobs, stk); + Item.legislation_id = legislation_id.join("::"); } - if (myblobs && myblobs.length) { - var last_suffix = myblobs[myblobs.length - 1].strings.suffix; - if (last_suffix) { - lastchr = last_suffix.slice(-1); + } + if (this.opt.development_extensions.main_title_from_short_title) { + Item["title-main"] = Item.title; + Item["title-sub"] = false; + if (Item.title && Item.shortTitle) { + offset = Item.shortTitle.length; + if (Item.title.slice(0,offset) === Item.shortTitle && Item.title.slice(offset).match(/^\s*:/)) { + Item["title-main"] = Item.title.slice(0,offset).replace(/\s+$/,""); + Item["title-sub"] = Item.title.slice(offset).replace(/^\s*:\s*/,""); } } } - if (stk.length > 1) { - stk.pop(); + if (!Item["title-short"]) { + Item["title-short"] = Item.shortTitle; } - state.tmp.last_chr = lastchr; - return lastchr; -}; -CSL.ambigConfigDiff = function(a, b) { - var ret, pos, len, ppos, llen; - if (a.names.length !== b.names.length) { - return 1; - } else { - for (pos = 0, len = a.names.length; pos < len; pos += 1) { - if (a.names[pos] !== b.names[pos]) { - return 1; - } else { - for (ppos = 0, llen = a.givens[pos]; ppos < llen; ppos += 1) { - if (a.givens[pos][ppos] !== b.givens[pos][ppos]) { - return 1; - } - } + var isLegalType = ["legal_case","legislation","gazette","regulation"].indexOf(Item.type) > -1; + if (!isLegalType && Item.title && this.sys.getAbbreviation) { + var jurisdiction = this.transform.loadAbbreviation(Item.jurisdiction, "title", Item.title); + if (this.transform.abbrevs[jurisdiction].title) { + if (this.transform.abbrevs[jurisdiction].title[Item.title]) { + Item["title-short"] = this.transform.abbrevs[jurisdiction].title[Item.title]; } } } - if (a.disambiguate != b.disambiguate) { - return 1; - } - if (a.year_suffix !== b.year_suffix) { - return 1; - } - return 0; -}; -CSL.cloneAmbigConfig = function (config, oldconfig, tainters) { - var i, ilen, j, jlen, k, klen, param; - var ret = {}; - ret.names = []; - ret.givens = []; - ret.year_suffix = false; - ret.disambiguate = false; - for (i = 0, ilen = config.names.length; i < ilen; i += 1) { - param = config.names[i]; - ret.names[i] = param; - } - for (i = 0, ilen = config.givens.length; i < ilen; i += 1) { - param = []; - for (j = 0, jlen = config.givens[i].length; j < jlen; j += 1) { - param.push(config.givens[i][j]); + Item["container-title-short"] = Item.journalAbbreviation; + if (Item["container-title"] && this.sys.getAbbreviation) { + var jurisdiction = this.transform.loadAbbreviation(Item.jurisdiction, "title", Item["container-title"]); + if (this.transform.abbrevs[jurisdiction].title) { + if (this.transform.abbrevs[jurisdiction].title[Item["container-title"]]) { + Item["container-title-short"] = this.transform.abbrevs[jurisdiction].title[Item["container-title"]]; + } } - ret.givens.push(param); - } - if (oldconfig) { - ret.year_suffix = oldconfig.year_suffix; - ret.disambiguate = oldconfig.disambiguate; - } else { - ret.year_suffix = config.year_suffix; - ret.disambiguate = config.disambiguate; } - return ret; + return Item; }; -CSL.getAmbigConfig = function () { - var config, ret; - config = this.tmp.disambig_request; - if (!config) { - config = this.tmp.disambig_settings; +CSL.Engine.prototype.setOpt = function (token, name, value) { + if (token.name === "style" || token.name === "cslstyle") { + this.opt[name] = value; + } else if (["citation", "bibliography"].indexOf(token.name) > -1) { + this[token.name].opt[name] = value; + } else if (["name-form", "name-delimiter", "names-delimiter"].indexOf(name) === -1) { + token.strings[name] = value; } - ret = CSL.cloneAmbigConfig(config); - return ret; -}; -CSL.getMaxVals = function () { - return this.tmp.names_max.mystack.slice(); }; -CSL.getMinVal = function () { - return this.tmp["et-al-min"]; -}; -CSL.tokenExec = function (token, Item, item) { - var next, maybenext, exec, pos, len, debug; - debug = false; - next = token.next; - maybenext = false; - if (token.evaluator) { - next = token.evaluator(token, this, Item, item); +CSL.Engine.prototype.fixOpt = function (token, name, localname) { + if (["citation", "bibliography"].indexOf(token.name) > -1) { + if (! this[token.name].opt[name] && "undefined" !== typeof this.opt[name]) { + this[token.name].opt[name] = this.opt[name]; + } } - len = token.execs.length; - for (pos = 0; pos < len; pos += 1) { - exec = token.execs[pos]; - maybenext = exec.call(token, this, Item, item); - if (maybenext) { - next = maybenext; + if ("name" === token.name || "names" === token.name) { + if ("undefined" === typeof token.strings[localname] && "undefined" !== typeof this[this.build.root].opt[name]) { + token.strings[localname] = this[this.build.root].opt[name]; } } - return next; }; -CSL.expandMacro = function (macro_key_token) { - var mkey, start_token, key, end_token, navi, macro_nodes, newoutput, mergeoutput, end_of_macro, func; - mkey = macro_key_token.postponed_macro; - if (this.build.macro_stack.indexOf(mkey) > -1) { - throw "CSL processor error: call to macro \"" + mkey + "\" would cause an infinite loop"; - } else { - this.build.macro_stack.push(mkey); - } - var hasDate = false; - var macroid = false; - macro_nodes = this.sys.xml.getNodesByName(this.cslXml, 'macro', mkey); - if (macro_nodes.length) { - macroid = this.sys.xml.getAttributeValue(macro_nodes[0],'cslid'); - hasDate = this.sys.xml.getAttributeValue(macro_nodes[0], "macro-has-date"); - } - if (hasDate) { - func = function (state, Item) { - if (state.tmp.extension) { - state.tmp["doing-macro-with-date"] = true; - } - }; - macro_key_token.execs.push(func); - } - macro_key_token.tokentype = CSL.START; - macro_key_token.cslid = macroid; - CSL.Node.group.build.call(macro_key_token, this, this[this.build.area].tokens, true); - if (!this.sys.xml.getNodeValue(macro_nodes)) { - throw "CSL style error: undefined macro \"" + mkey + "\""; - } - navi = new this.getNavi(this, macro_nodes); - CSL.buildStyle.call(this, navi); - end_of_macro = new CSL.Token("group", CSL.END); - if (macro_key_token.decorations) { - end_of_macro.decorations = macro_key_token.decorations.slice(); - } - if (hasDate) { - func = function (state, Item) { - if (state.tmp.extension) { - state.tmp["doing-macro-with-date"] = false; +CSL.Engine.prototype.remapSectionVariable = function (inputList) { + for (var i = 0, ilen = inputList.length; i < ilen; i += 1) { + var Item = inputList[i][0]; + var item = inputList[i][1]; + var section_label_count = 0; + var later_label = false; + var value = false; + if (["bill","gazette","legislation","treaty"].indexOf(Item.type) > -1) { + item.force_pluralism = 0; + if (!item.label) { + item.label = "page" } - }; - end_of_macro.execs.push(func); - } - CSL.Node.group.build.call(end_of_macro, this, this[this.build.area].tokens, true); - this.build.macro_stack.pop(); -}; -CSL.XmlToToken = function (state, tokentype) { - var name, txt, attrfuncs, attributes, decorations, token, key, target; - name = state.sys.xml.nodename(this); - if (state.build.skip && state.build.skip !== name) { - return; - } - if (!name) { - txt = state.sys.xml.content(this); - if (txt) { - state.build.text = txt; - } - return; - } - if (!CSL.Node[state.sys.xml.nodename(this)]) { - throw "Undefined node name \"" + name + "\"."; - } - attrfuncs = []; - attributes = state.sys.xml.attributes(this); - decorations = CSL.setDecorations.call(this, state, attributes); - token = new CSL.Token(name, tokentype); - if (tokentype !== CSL.END || name === "if" || name === "else-if" || name === "layout") { - for (key in attributes) { - if (attributes.hasOwnProperty(key)) { - if (tokentype === CSL.END && key !== "@language" && key !== "@locale") { - continue; - } - if (attributes.hasOwnProperty(key)) { - if (CSL.Attributes[key]) { - try { - CSL.Attributes[key].call(token, state, "" + attributes[key]); - } catch (e) { - CSL.error(e); - throw "CSL processor error, " + key + " attribute: " + e; - } - } else { - CSL.debug("warning: undefined attribute \""+key+"\" in style"); - } + var loci = ["section","","",""]; + var split; + if (this.opt.development_extensions.static_statute_locator && Item.section) { + splt = Item.section.replace(/^\s+/,"").replace(/\s+$/, "").split(/\s+/); + if (CSL.STATUTE_SUBDIV_STRINGS[splt[0]]) { + loci[0] = " " + splt[0] + " "; + loci[1] = splt.slice(1).join(" "); + } else { + loci[0] = " sec. "; + loci[1] = splt.slice(0).join(" "); + } + } else { + if (this.opt.development_extensions.clobber_locator_if_no_statute_section) { + item.locator = undefined; + item.label = undefined; } } - } - token.decorations = decorations; - } - target = state[state.build.area].tokens; - CSL.Node[name].build.call(token, state, target); -}; -CSL.DateParser = function () { - var jiy_list, jiy, jiysplitter, jy, jmd, jr, pos, key, val, yearlast, yearfirst, number, rangesep, fuzzychar, chars, rex, rexdash, rexdashslash, rexslashdash, seasonstrs, seasonrexes, seasonstr, monthstrs, monthstr, mrexes, seasonrex, len, jiymatchstring, jiymatcher; - jiy_list = [ - ["\u660E\u6CBB", 1867], - ["\u5927\u6B63", 1911], - ["\u662D\u548C", 1925], - ["\u5E73\u6210", 1988] - ]; - jiy = {}; - len = jiy_list.length; - for (pos = 0; pos < len; pos += 1) { - key = jiy_list[pos][0]; - val = jiy_list[pos][1]; - jiy[key] = val; - } - jiymatchstring = []; - for (pos = 0; pos < len; pos += 1) { - val = jiy_list[pos][0]; - jiymatchstring.push(val); - } - jiymatchstring = jiymatchstring.join("|"); - jiysplitter = "(?:" + jiymatchstring + ")(?:[0-9]+)"; - jiysplitter = new RegExp(jiysplitter); - jiymatcher = "(?:" + jiymatchstring + ")(?:[0-9]+)"; - jiymatcher = new RegExp(jiymatcher, "g"); - jmd = /(\u6708|\u5E74)/g; - jy = /\u65E5/; - jr = /\u301c/g; - yearlast = "(?:[?0-9]{1,2}%%NUMD%%){0,2}[?0-9]{4}(?![0-9])"; - yearfirst = "[?0-9]{4}(?:%%NUMD%%[?0-9]{1,2}){0,2}(?![0-9])"; - number = "[?0-9]{1,3}"; - rangesep = "[%%DATED%%]"; - fuzzychar = "[?~]"; - chars = "[a-zA-Z]+"; - rex = "(" + yearfirst + "|" + yearlast + "|" + number + "|" + rangesep + "|" + fuzzychar + "|" + chars + ")"; - rexdash = new RegExp(rex.replace(/%%NUMD%%/g, "-").replace(/%%DATED%%/g, "-")); - rexdashslash = new RegExp(rex.replace(/%%NUMD%%/g, "-").replace(/%%DATED%%/g, "\/")); - rexslashdash = new RegExp(rex.replace(/%%NUMD%%/g, "\/").replace(/%%DATED%%/g, "-")); - seasonstrs = []; - seasonrexes = []; - len = seasonstrs.length; - for (pos = 0; pos < len; pos += 1) { - seasonrex = new RegExp(seasonstrs[pos] + ".*"); - seasonrexes.push(seasonrex); - } - this.mstrings = "january february march april may june july august september october november december spring summer fall winter spring summer"; - this.mstrings = this.mstrings.split(" "); - this.setOrderDayMonth = function() { - this.monthguess = 1; - this.dayguess = 0; - }; - this.setOrderMonthDay = function() { - this.monthguess = 0; - this.dayguess = 1; - }; - this.setOrderMonthDay(); - this.resetMonths = function() { - var i, ilen, j, jlen; - this.msets = []; - for (i = 0, ilen = this.mstrings.length; i < ilen; i += 1) { - this.msets.push([this.mstrings[i]]); - } - this.mabbrevs = []; - for (i = 0, ilen = this.msets.length; i < ilen; i += 1) { - this.mabbrevs.push([]); - for (j = 0, jlen = this.msets[i].length; j < jlen; j += 1) { - this.mabbrevs[i].push(this.msets[i][0].slice(0, 3)); - } - } - this.mrexes = []; - for (i = 0, ilen = this.mabbrevs.length; i < ilen; i += 1) { - this.mrexes.push(new RegExp("(?:" + this.mabbrevs[i].join("|") + ")")); - } - }; - this.resetMonths(); - this.addMonths = function(lst) { - var i, ilen, j, jlen, k, klen, jkey, kkey; - if ("string" === typeof lst) { - lst = lst.split(/\s+/); - } - if (lst.length !== 12 && lst.length !== 16) { - CSL.debug("month [+season] list of "+lst.length+", expected 12 or 16. Ignoring."); - return; - } - var othermatch = []; - var thismatch = []; - for (i = 0, ilen = lst.length; i < ilen; i += 1) { - var abbrevlen = false; - var skip = false; - var insert = 3; - var extend = {}; - for (j = 0, jlen = this.mabbrevs.length; j < jlen; j += 1) { - extend[j] = {}; - if (j === i) { - for (k = 0, klen = this.mabbrevs[i].length; k < klen; k += 1) { - if (this.mabbrevs[i][k] === lst[i].slice(0, this.mabbrevs[i][k].length)) { - skip = true; - break; - } - } + if (item.locator) { + var splt = item.locator.replace(/^\s+/,"").replace(/\s+$/, "").split(/\s+/); + if (CSL.STATUTE_SUBDIV_STRINGS[splt[0]]) { + loci[2] = " " + splt[0] + " "; + loci[3] = splt.slice(1).join(" "); + } else if (item.label) { + loci[2] = " " + CSL.STATUTE_SUBDIV_STRINGS_REVERSE[item.label] + " "; + loci[3] = splt.slice(0).join(" "); } else { - for (k = 0, klen = this.mabbrevs[j].length; k < klen; k += 1) { - abbrevlen = this.mabbrevs[j][k].length; - if (this.mabbrevs[j][k] === lst[i].slice(0, abbrevlen)) { - while (this.msets[j][k].slice(0, abbrevlen) === lst[i].slice(0, abbrevlen)) { - if (abbrevlen > lst[i].length || abbrevlen > this.msets[j][k].length) { - CSL.debug("unable to disambiguate month string in date parser: "+lst[i]); - break; - } else { - abbrevlen += 1; - } - } - insert = abbrevlen; - extend[j][k] = abbrevlen; - } - } + loci[3] = splt.join(" ") } - for (jkey in extend) { - if (extend.hasOwnProperty(jkey)) { - for (kkey in extend[jkey]) { - if (extend[jkey].hasOwnProperty(kkey)) { - abbrevlen = extend[jkey][kkey]; - jkey = parseInt(jkey, 10); - kkey = parseInt(kkey, 10); - this.mabbrevs[jkey][kkey] = this.msets[jkey][kkey].slice(0, abbrevlen); - } - } - } + if (loci[3] && loci[3].slice(0,1) === "&") { + loci[3] = " " + loci[3]; } } - if (!skip) { - this.msets[i].push(lst[i]); - this.mabbrevs[i].push(lst[i].slice(0, insert)); + if (!loci[2]) { + loci[2] = loci[0]; } - } - this.mrexes = []; - for (i = 0, ilen = this.mabbrevs.length; i < ilen; i += 1) { - this.mrexes.push(new RegExp("(?:" + this.mabbrevs[i].join("|") + ")")); - } - }; - this.parse = function (txt) { - var slash, dash, lst, l, m, number, note, thedate, slashcount, range_delim, date_delim, ret, delim_pos, delims, isrange, suff, date, breakme, item, delim, element, mm, slst, mmpos, i, ilen, j, jlen, k, klen; - if (txt) { - txt = "" + txt; - txt = txt.replace(/\s*[0-9]{2}:[0-9]{2}(?::[0-9]+)/,""); - m = txt.match(jmd); - if (m) { - txt = txt.replace(/\s+/, "", "g"); - txt = txt.replace(jy, "", "g"); - txt = txt.replace(jmd, "-", "g"); - txt = txt.replace(jr, "/", "g"); - txt = txt.replace("-/", "/", "g"); - txt = txt.replace(/-$/,"", "g"); - slst = txt.split(jiysplitter); - lst = []; - mm = txt.match(jiymatcher); - if (mm) { - var mmx = []; - for (pos = 0, len = mm.length; pos < len; pos += 1) { - mmx = mmx.concat(mm[pos].match(/([^0-9]+)([0-9]+)/).slice(1)); - } - for (pos = 0, len = slst.length; pos < len; pos += 1) { - lst.push(slst[pos]); - if (pos !== (len - 1)) { - mmpos = (pos * 2); - lst.push(mmx[mmpos]); - lst.push(mmx[mmpos + 1]); + if (loci[3]) { + if (loci[3].match(/^[^0-9a-zA-Z]/)) { + var loclst = loci[3].split(/\s+/); + if (loci[0] === loci[2] && loclst[1] && !CSL.STATUTE_SUBDIV_STRINGS[loclst[1].replace(/\s+/, "").replace(/\s+/, "")]) { + item.force_pluralism = 1; } + loci[2] = ""; } } else { - lst = slst; + loci[2] = ""; } - l = lst.length; - for (pos = 1; pos < l; pos += 3) { - lst[pos + 1] = jiy[lst[pos]] + parseInt(lst[pos + 1], 10); - lst[pos] = ""; + if (!loci[1]) { + loci[0] = ""; } - txt = lst.join(""); - txt = txt.replace(/\s*-\s*$/, "").replace(/\s*-\s*\//, "/"); - txt = txt.replace(/\.\s*$/, ""); - txt = txt.replace(/\.(?! )/, ""); - slash = txt.indexOf("/"); - dash = txt.indexOf("-"); - } - } - txt = txt.replace(/([A-Za-z])\./g, "$1"); - number = ""; - note = ""; - thedate = {}; - if (txt.slice(0, 1) === "\"" && txt.slice(-1) === "\"") { - thedate.literal = txt.slice(1, -1); - return thedate; - } - if (slash > -1 && dash > -1) { - slashcount = txt.split("/"); - if (slashcount.length > 3) { - range_delim = "-"; - date_delim = "/"; - lst = txt.split(rexslashdash); - } else { - range_delim = "/"; - date_delim = "-"; - lst = txt.split(rexdashslash); + var value = loci.join(""); + value = value.replace(/^\s+/,"").replace(/\s+$/, ""); + if (value) { + splt = value.split(/\s+/); + if (CSL.STATUTE_SUBDIV_STRINGS[splt[0]]) { + var has_other = false; + for (var j = splt.length - 2; j > 0; j += -2) { + if (splt[j] === splt[0]) { + item.force_pluralism = 1; + splt = splt.slice(0,j).concat(splt.slice(j + 1)); + } + } + item.label = CSL.STATUTE_SUBDIV_STRINGS[splt[0]]; + item.locator = splt.slice(1).join(" "); + if (item.force_pluralism === 0) { + delete item.force_pluralism; + } + } else { + item.locator = splt.slice(0).join(" "); + } } - } else { - txt = txt.replace("/", "-"); - range_delim = "-"; - date_delim = "-"; - lst = txt.split(rexdash); } - ret = []; - len = lst.length; - for (pos = 0; pos < len; pos += 1) { - item = lst[pos]; - m = item.match(/^\s*([\-\/]|[a-zA-Z]+|[\-~?0-9]+)\s*$/); - if (m) { - ret.push(m[1]); + } +} +CSL.Engine.prototype.setNumberLabels = function (Item) { + if (Item.number + && ["bill", "gazette", "legislation", "treaty"].indexOf(Item.type) > -1 + && this.opt.development_extensions.static_statute_locator + && !this.tmp.shadow_numbers["number"]) { + this.tmp.shadow_numbers["number"] = {}; + this.tmp.shadow_numbers["number"].values = []; + this.tmp.shadow_numbers["number"].plural = 0; + this.tmp.shadow_numbers["number"].numeric = false; + this.tmp.shadow_numbers["number"].label = false; + var value = "" + Item.number; + value = value.replace("\\", "", "g"); + var firstword = value.split(/\s/)[0]; + var firstlabel = CSL.STATUTE_SUBDIV_STRINGS[firstword]; + if (firstlabel) { + var m = value.match(CSL.STATUTE_SUBDIV_GROUPED_REGEX); + var splt = value.split(CSL.STATUTE_SUBDIV_PLAIN_REGEX); + if (splt.length > 1) { + var lst = []; + for (var j=1, jlen=splt.length; j < jlen; j += 1) { + var subdiv = m[j - 1].replace(/^\s*/, ""); + lst.push(subdiv.replace("sec.", "Sec.").replace("ch.", "Ch.")); + lst.push(splt[j].replace(/\s*$/, "").replace(/^\s*/, "")); + } + value = lst.join(" "); + } else { + value = splt[0]; } + this.tmp.shadow_numbers["number"].values.push(["Blob", value, false]); + this.tmp.shadow_numbers["number"].numeric = false; + } else { + this.tmp.shadow_numbers["number"].values.push(["Blob", value, false]); + this.tmp.shadow_numbers["number"].numeric = true; } - delim_pos = ret.indexOf(range_delim); - delims = []; - isrange = false; - if (delim_pos > -1) { - delims.push([0, delim_pos]); - delims.push([(delim_pos + 1), ret.length]); - isrange = true; + } +} +CSL.substituteOne = function (template) { + return function (state, list) { + if (!list) { + return ""; } else { - delims.push([0, ret.length]); + return template.replace("%%STRING%%", list); } - suff = ""; - for (i = 0, ilen = delims.length; i < ilen; i += 1) { - delim = delims[i]; - date = ret.slice(delim[0], delim[1]); - for (j = 0, jlen = date.length; j < jlen; j += 1) { - element = date[j]; - if (element.indexOf(date_delim) > -1) { - this.parseNumericDate(thedate, date_delim, suff, element); - continue; - } - if (element.match(/[0-9]{4}/)) { - thedate[("year" + suff)] = element.replace(/^0*/, ""); - continue; - } - breakme = false; - for (k = 0, klen = this.mrexes.length; k < klen; k += 1) { - if (element.toLocaleLowerCase().match(this.mrexes[k])) { - thedate[("month" + suff)] = "" + (parseInt(k, 10) + 1); - breakme = true; - break; - } - if (breakme) { - continue; - } - if (element.match(/^[0-9]+$/)) { - number = parseInt(element, 10); - } - if (element.toLocaleLowerCase().match(/^bc/) && number) { - thedate[("year" + suff)] = "" + (number * -1); - number = ""; - continue; - } - if (element.toLocaleLowerCase().match(/^ad/) && number) { - thedate[("year" + suff)] = "" + number; - number = ""; - continue; - } - } - breakme = false; - for (k = 0, klen = seasonrexes.length; k < klen; k += 1) { - if (element.toLocaleLowerCase().match(seasonrexes[k])) { - thedate[("season" + suff)] = "" + (parseInt(k, 10) + 1); - breakme = true; - break; - } - } - if (breakme) { - continue; - } - if (element === "~" || element === "?" || element === "c" || element.match(/^cir/)) { - thedate.circa = "" + 1; - continue; - } - if (element.toLocaleLowerCase().match(/(?:mic|tri|hil|eas)/) && !thedate[("season" + suff)]) { - note = element; - continue; - } + }; +}; +CSL.substituteTwo = function (template) { + return function (param) { + var template2 = template.replace("%%PARAM%%", param); + return function (state, list) { + if (!list) { + return ""; + } else { + return template2.replace("%%STRING%%", list); } - if (number) { - thedate[("day" + suff)] = number; - number = ""; + }; + }; +}; +CSL.Mode = function (mode) { + var decorations, params, param, func, val, args; + decorations = {}; + params = CSL.Output.Formats[mode]; + for (param in params) { + if (true) { + if ("@" !== param.slice(0, 1)) { + decorations[param] = params[param]; + continue; } - if (note && !thedate[("season" + suff)]) { - thedate[("season" + suff)] = note; - note = ""; + func = false; + val = params[param]; + args = param.split('/'); + if (typeof val === "string" && val.indexOf("%%STRING%%") > -1) { + if (val.indexOf("%%PARAM%%") > -1) { + func = CSL.substituteTwo(val); + } else { + func = CSL.substituteOne(val); + } + } else if (typeof val === "boolean" && !val) { + func = CSL.Output.Formatters.passthrough; + } else if (typeof val === "function") { + func = val; + } else { + throw "CSL.Compiler: Bad " + mode + " config entry for " + param + ": " + val; } - suff = "_end"; - } - if (isrange) { - for (j = 0, jlen = CSL.DATE_PARTS_ALL.length; j < jlen; j += 1) { - item = CSL.DATE_PARTS_ALL[j]; - if (thedate[item] && !thedate[(item + "_end")]) { - thedate[(item + "_end")] = thedate[item]; - } else if (!thedate[item] && thedate[(item + "_end")]) { - thedate[item] = thedate[(item + "_end")]; + if (args.length === 1) { + decorations[args[0]] = func; + } else if (args.length === 2) { + if (!decorations[args[0]]) { + decorations[args[0]] = {}; } + decorations[args[0]][args[1]] = func; } } - if (!thedate.year) { - thedate = { "literal": txt }; - } - if (this.use_array) { - this.toArray(thedate); - } - return thedate; - }; - this.returnAsArray = function () { - this.use_array = true; - }; - this.returnAsKeys = function () { - this.use_array = false; - }; - this.toArray = function (thedate) { - var i, ilen, part; - thedate["date-parts"] = []; - thedate["date-parts"].push([]); - var slicelen = 0; - for (i = 0, ilen = 3; i < ilen; i += 1) { - part = ["year", "month", "day"][i]; - if (!thedate[part]) { - break; + } + return decorations; +}; +CSL.setDecorations = function (state, attributes) { + var ret, key, pos; + ret = []; + for (pos in CSL.FORMAT_KEY_SEQUENCE) { + if (true) { + key = CSL.FORMAT_KEY_SEQUENCE[pos]; + if (attributes[key]) { + ret.push([key, attributes[key]]); + delete attributes[key]; } - slicelen += 1; - thedate["date-parts"][0].push(thedate[part]); - delete thedate[part]; } - for (i = 0, ilen = slicelen; i < ilen; i += 1) { - part = ["year_end", "month_end", "day_end"][i]; - if (thedate[part] && thedate["date-parts"].length === 1) { - thedate["date-parts"].push([]); - } - thedate["date-parts"][1].push(thedate[part]); - delete thedate[part]; + } + return ret; +}; +CSL.Engine.prototype.normalDecorIsOrphan = function (blob, params) { + if (params[1] === "normal") { + var use_param = false; + var all_the_decor; + if (this.tmp.area === "citation") { + all_the_decor = [this.citation.opt.layout_decorations].concat(blob.alldecor); + } else { + all_the_decor = blob.alldecor; } - }; - this.parseNumericDate = function (ret, delim, suff, txt) { - var lst, i, ilen; - lst = txt.split(delim); - for (i = 0, ilen = lst.length; i < ilen; i += 1) { - if (lst[i].length === 4) { - ret[("year" + suff)] = lst[i].replace(/^0*/, ""); - if (!i) { - lst = lst.slice(1); - } else { - lst = lst.slice(0, i); + for (var k = all_the_decor.length - 1; k > -1; k += -1) { + for (var n = all_the_decor[k].length - 1; n > -1; n += -1) { + if (all_the_decor[k][n][0] === params[0]) { + if (all_the_decor[k][n][1] !== "normal") { + use_param = true; + } } - break; } } - for (i = 0, ilen = lst.length; i < ilen; i += 1) { - lst[i] = parseInt(lst[i], 10); - } - if (lst.length === 1 || (lst.length === 2 && !lst[1])) { - ret[("month" + suff)] = "" + lst[0]; - } else if (lst.length === 2) { - if (lst[this.monthguess] > 12) { - ret[("month" + suff)] = "" + lst[this.dayguess]; - ret[("day" + suff)] = "" + lst[this.monthguess]; - } else { - ret[("month" + suff)] = "" + lst[this.monthguess]; - ret[("day" + suff)] = "" + lst[this.dayguess]; - } + if (!use_param) { + return true; } - }; -}; -CSL.Engine = function (sys, style, lang, forceLang) { - var attrs, langspec, localexml, locale; - this.processor_version = CSL.PROCESSOR_VERSION; - this.csl_version = "1.0"; - this.sys = sys; - this.sys.xml = new CSL.System.Xml.Parsing(); - if ("undefined" === typeof CSL_JSON && "string" !== typeof style) { - style = ""; - } - if (CSL.getAbbreviation) { - this.sys.getAbbreviation = CSL.getAbbreviation; } - if (this.sys.stringCompare) { - CSL.stringCompare = this.sys.stringCompare; + return false; +}; +CSL.Engine.prototype.getCitationLabel = function (Item) { + var label = ""; + var params = this.getTrigraphParams(); + var config = params[0]; + var myname = this.getTerm("reference", "short", 0); + if ("undefined" === typeof myname) { + myname = "reference"; } - this.sys.AbbreviationSegments = CSL.AbbreviationSegments; - this.parallel = new CSL.Parallel(this); - this.transform = new CSL.Transform(this); - this.setParseNames = function (val) { - this.opt['parse-names'] = val; - }; - this.opt = new CSL.Engine.Opt(); - this.tmp = new CSL.Engine.Tmp(); - this.build = new CSL.Engine.Build(); - this.fun = new CSL.Engine.Fun(this); - this.configure = new CSL.Engine.Configure(); - this.citation_sort = new CSL.Engine.CitationSort(); - this.bibliography_sort = new CSL.Engine.BibliographySort(); - this.citation = new CSL.Engine.Citation(this); - this.bibliography = new CSL.Engine.Bibliography(); - this.output = new CSL.Output.Queue(this); - this.dateput = new CSL.Output.Queue(this); - this.cslXml = this.sys.xml.makeXml(style); - if (this.opt.development_extensions.csl_reverse_lookup_support) { - this.build.cslNodeId = 0; - this.setCslNodeIds = function(myxml, nodename) { - var children = this.sys.xml.children(myxml); - this.sys.xml.setAttribute(myxml, 'cslid', this.build.cslNodeId); - this.opt.nodenames.push(nodename); - this.build.cslNodeId += 1; - for (var i = 0, ilen = this.sys.xml.numberofnodes(children); i < ilen; i += 1) { - nodename = this.sys.xml.nodename(children[i]); - if (nodename) { - this.setCslNodeIds(children[i], nodename); + myname = myname.replace(".", ""); + myname = myname.slice(0, 1).toUpperCase() + myname.slice(1); + for (var i = 0, ilen = CSL.CREATORS.length; i < ilen; i += 1) { + var n = CSL.CREATORS[i]; + if (Item[n]) { + var names = Item[n]; + if (names.length > params.length) { + config = params[params.length - 1]; + } else { + config = params[names.length - 1]; + } + for (var j = 0, jlen = names.length; j < jlen; j += 1) { + if (j === config.authors.length) { + break; + } + var res = this.nameOutput.getName(names[j], "locale-translit", true); + var name = res.name; + if (name && name.family) { + myname = name.family; + myname = myname.replace(/^([ \'\u2019a-z]+\s+)/, ""); + } else if (name && name.literal) { + myname = name.literal; + } + var m = myname.toLowerCase().match(/^(a\s+|the\s+|an\s+)/); + if (m) { + myname = myname.slice(m[1].length); + } + myname = myname.replace(CSL.ROMANESQUE_NOT_REGEXP, "", "g"); + if (!myname) { + break; + } + myname = myname.slice(0, config.authors[j]); + if (myname.length > 1) { + myname = myname.slice(0, 1).toUpperCase() + myname.slice(1).toLowerCase(); + } else if (myname.length === 1) { + myname = myname.toUpperCase(); } + label += myname; } - }; - this.setCslNodeIds(this.cslXml, "style"); - } - this.sys.xml.addMissingNameNodes(this.cslXml); - this.sys.xml.addInstitutionNodes(this.cslXml); - this.sys.xml.insertPublisherAndPlace(this.cslXml); - this.sys.xml.flagDateMacros(this.cslXml); - attrs = this.sys.xml.attributes(this.cslXml); - if ("undefined" === typeof attrs["@sort-separator"]) { - this.sys.xml.setAttribute(this.cslXml, "sort-separator", ", "); - } - this.opt["initialize-with-hyphen"] = true; - this.setStyleAttributes(); - this.opt.xclass = sys.xml.getAttributeValue(this.cslXml, "class"); - this.opt.styleID = this.sys.xml.getStyleId(this.cslXml); - if (lang) { - lang = lang.replace("_", "-"); - } - if (this.opt["default-locale"][0]) { - this.opt["default-locale"][0] = this.opt["default-locale"][0].replace("_", "-"); + break; + } } - if (lang && forceLang) { - this.opt["default-locale"] = [lang]; + var year = "0000"; + if (Item.issued) { + if (Item.issued.year) { + year = "" + Item.issued.year; + } } - if (lang && !forceLang && this.opt["default-locale"][0]) { - lang = this.opt["default-locale"][0]; + year = year.slice((config.year * -1)); + label = label + year; + return label; +}; +CSL.Engine.prototype.getTrigraphParams = function () { + var params = []; + var ilst = this.opt.trigraph.split(":"); + if (!this.opt.trigraph || this.opt.trigraph.slice(0,1) !== "A") { + throw "Bad trigraph definition: "+this.opt.trigraph; } - if (this.opt["default-locale"].length === 0) { - if (!lang) { - lang = "en-US"; + for (var i = 0, ilen = ilst.length; i < ilen; i += 1) { + var str = ilst[i]; + var config = {authors:[], year:0}; + for (var j = 0, jlen = str.length; j < jlen; j += 1) { + switch (str.slice(j,j+1)) { + case "A": + config.authors.push(1); + break; + case "a": + config.authors[config.authors.length - 1] += 1; + break; + case "0": + config.year += 1; + break; + default: + throw "Invalid character in trigraph definition: "+this.opt.trigraph; + } } - this.opt["default-locale"].push("en-US"); - } - if (!lang) { - lang = this.opt["default-locale"][0]; + params.push(config); } - langspec = CSL.localeResolve(lang); - this.opt.lang = langspec.best; - this.opt["default-locale"][0] = langspec.best; - this.locale = {}; - this.localeConfigure(langspec); - this.registry = new CSL.Registry(this); - this.buildTokenLists("citation"); - this.buildTokenLists("bibliography"); - this.configureTokenLists(); - this.disambiguate = new CSL.Disambiguation(this); - this.splice_delimiter = false; - this.fun.dateparser = new CSL.DateParser(); - this.fun.flipflopper = new CSL.Util.FlipFlopper(this); - this.setCloseQuotesArray(); - this.fun.ordinalizer.init(this); - this.fun.long_ordinalizer.init(this); - this.fun.page_mangler = CSL.Util.PageRangeMangler.getFunction(this, "page"); - this.fun.year_mangler = CSL.Util.PageRangeMangler.getFunction(this, "year"); - this.setOutputFormat("html"); -}; -CSL.Engine.prototype.setCloseQuotesArray = function () { - var ret; - ret = []; - ret.push(this.getTerm("close-quote")); - ret.push(this.getTerm("close-inner-quote")); - ret.push('"'); - ret.push("'"); - this.opt.close_quotes_array = ret; + return params; }; -CSL.Engine.prototype.buildTokenLists = function (area) { - var area_nodes, navi; - area_nodes = this.sys.xml.getNodesByName(this.cslXml, area); - if (!this.sys.xml.getNodeValue(area_nodes)) { - return; +CSL.Engine.prototype.setOutputFormat = function (mode) { + this.opt.mode = mode; + this.fun.decorate = CSL.Mode(mode); + if (!this.output[mode]) { + this.output[mode] = {}; + this.output[mode].tmp = {}; } - navi = new this.getNavi(this, area_nodes); - this.build.area = area; - CSL.buildStyle.call(this, navi); }; -CSL.Engine.prototype.setStyleAttributes = function () { - var dummy, attr, key, attributes, attrname; - dummy = {}; - dummy.name = this.sys.xml.nodename(this.cslXml); - attributes = this.sys.xml.attributes(this.cslXml); - for (attrname in attributes) { - if (attributes.hasOwnProperty(attrname)) { - CSL.Attributes[attrname].call(dummy, this, attributes[attrname]); +CSL.Engine.prototype.setLangTagsForCslSort = function (tags) { + var i, ilen; + if (tags) { + this.opt['locale-sort'] = []; + for (i = 0, ilen = tags.length; i < ilen; i += 1) { + this.opt['locale-sort'].push(tags[i]); } } }; -CSL.buildStyle = function (navi) { - if (navi.getkids()) { - CSL.buildStyle.call(this, navi); - } else { - if (navi.getbro()) { - CSL.buildStyle.call(this, navi); - } else { - while (navi.nodeList.length > 1) { - if (navi.remember()) { - CSL.buildStyle.call(this, navi); - } - } +CSL.Engine.prototype.setLangTagsForCslTransliteration = function (tags) { + var i, ilen; + this.opt['locale-translit'] = []; + if (tags) { + for (i = 0, ilen = tags.length; i < ilen; i += 1) { + this.opt['locale-translit'].push(tags[i]); } } }; -CSL.Engine.prototype.getNavi = function (state, myxml) { - this.sys = state.sys; - this.state = state; - this.nodeList = []; - this.nodeList.push([0, myxml]); - this.depth = 0; -}; -CSL.Engine.prototype.getNavi.prototype.remember = function () { - var node; - this.depth += -1; - this.nodeList.pop(); - node = this.nodeList[this.depth][1][(this.nodeList[this.depth][0])]; - CSL.XmlToToken.call(node, this.state, CSL.END); - return this.getbro(); +CSL.Engine.prototype.setLangTagsForCslTranslation = function (tags) { + var i, ilen; + this.opt['locale-translat'] = []; + if (tags) { + for (i = 0, ilen = tags.length; i < ilen; i += 1) { + this.opt['locale-translat'].push(tags[i]); + } + } }; -CSL.Engine.prototype.getNavi.prototype.getbro = function () { - var sneakpeek; - sneakpeek = this.nodeList[this.depth][1][(this.nodeList[this.depth][0] + 1)]; - if (sneakpeek) { - this.nodeList[this.depth][0] += 1; - return true; - } else { - return false; +CSL.Engine.prototype.setLangPrefsForCites = function (obj, conv) { + var opt = this.opt['cite-lang-prefs']; + if (!conv) { + conv = function (key) { + return key.toLowerCase(); + }; } -}; -CSL.Engine.prototype.getNavi.prototype.getkids = function () { - var currnode, sneakpeek, pos, node, len; - currnode = this.nodeList[this.depth][1][this.nodeList[this.depth][0]]; - sneakpeek = this.sys.xml.children(currnode); - if (this.sys.xml.numberofnodes(sneakpeek) === 0) { - if (this.depth) { - CSL.XmlToToken.call(currnode, this.state, CSL.SINGLETON); + var segments = ['Persons', 'Institutions', 'Titles', 'Publishers', 'Places']; + for (var i = 0, ilen = segments.length; i < ilen; i += 1) { + var clientSegment = conv(segments[i]); + var citeprocSegment = segments[i].toLowerCase(); + if (!obj[clientSegment]) { + continue; } - return false; - } else { - for (pos in sneakpeek) { - node = sneakpeek[pos]; - if ("date" === this.sys.xml.nodename(node)) { - currnode = CSL.Util.fixDateNode.call(this, currnode, pos, node); - sneakpeek = this.sys.xml.children(currnode); - } + var supplements = []; + while (obj[clientSegment].length > 1) { + supplements.push(obj[clientSegment].pop()); + } + var sortval = {orig:1,translit:2,translat:3}; + if (supplements.length === 2 && sortval[supplements[0]] < sortval[supplements[1]]) { + supplements.reverse(); + } + while (supplements.length) { + obj[clientSegment].push(supplements.pop()); + } + var lst = opt[citeprocSegment]; + while (lst.length) { + lst.pop(); + } + for (var j = 0, jlen = obj[clientSegment].length; j < jlen; j += 1) { + lst.push(obj[clientSegment][j]); } - CSL.XmlToToken.call(currnode, this.state, CSL.START); - this.depth += 1; - this.nodeList.push([0, sneakpeek]); - return true; } }; -CSL.Engine.prototype.getNavi.prototype.getNodeListValue = function () { - return this.nodeList[this.depth][1]; -}; -CSL.Engine.prototype.getTerm = function (term, form, plural, gender, mode, forceDefaultLocale) { - if (term && term.match(/[A-Z]/) && term === term.toUpperCase()) { - CSL.debug("Warning: term key is in uppercase form: "+term); - term = term.toLowerCase(); - } - var lang; - if (forceDefaultLocale) { - lang = this.opt["default-locale"][0]; - } else { - lang = this.opt.lang; - } - var ret = CSL.Engine.getField(CSL.LOOSE, this.locale[lang].terms, term, form, plural, gender); - if (!ret && term === "range-delimiter") { - ret = "\u2013"; - } - if (typeof ret === "undefined") { - if (mode === CSL.STRICT) { - throw "Error in getTerm: term \"" + term + "\" does not exist."; - } else if (mode === CSL.TOLERANT) { - ret = ""; +CSL.Engine.prototype.setLangPrefsForCiteAffixes = function (affixList) { + if (affixList && affixList.length === 40) { + var affixes = this.opt.citeAffixes; + var count = 0; + var settings = ["persons", "institutions", "titles", "publishers", "places"]; + var forms = ["translit", "orig", "translit", "translat"]; + var value; + for (var i = 0, ilen = settings.length; i < ilen; i += 1) { + for (var j = 0, jlen = forms.length; j < jlen; j += 1) { + value = ""; + if ((count % 8) === 4) { + if (!affixes[settings[i]]["locale-"+forms[j]].prefix + && !affixes[settings[i]]["locale-"+forms[j]].suffix) { + value = affixList[count] ? affixList[count] : ""; + affixes[settings[i]]["locale-" + forms[j]].prefix = value; + value = affixList[count] ? affixList[count + 1] : ""; + affixes[settings[i]]["locale-" + forms[j]].suffix = value; + } + } else { + value = affixList[count] ? affixList[count] : ""; + affixes[settings[i]]["locale-" + forms[j]].prefix = value; + value = affixList[count] ? affixList[count + 1] : ""; + affixes[settings[i]]["locale-" + forms[j]].suffix = value; + } + count += 2; + } } + this.opt.citeAffixes = affixes; } - if (ret) { - this.tmp.cite_renders_content = true; - } - return ret; }; -CSL.Engine.prototype.getDate = function (form, forceDefaultLocale) { - var lang; - if (forceDefaultLocale) { - lang = this.opt["default-locale"]; - } else { - lang = this.opt.lang; - } - if (this.locale[lang].dates[form]) { - return this.locale[lang].dates[form]; +CSL.Engine.prototype.setAutoVietnameseNamesOption = function (arg) { + if (arg) { + this.opt["auto-vietnamese-names"] = true; } else { - return false; + this.opt["auto-vietnamese-names"] = false; } }; -CSL.Engine.prototype.getOpt = function (arg) { - if ("undefined" !== typeof this.locale[this.opt.lang].opts[arg]) { - return this.locale[this.opt.lang].opts[arg]; - } else { - return false; +CSL.Engine.prototype.setAbbreviations = function (arg) { + if (this.sys.setAbbreviations) { + this.sys.setAbbreviations(arg); } }; -CSL.Engine.prototype.getVariable = function (Item, varname, form, plural) { - return CSL.Engine.getField(CSL.LOOSE, Item, varname, form, plural); +CSL.Output = {}; +CSL.Output.Queue = function (state) { + this.levelname = ["top"]; + this.state = state; + this.queue = []; + this.empty = new CSL.Token("empty"); + var tokenstore = {}; + tokenstore.empty = this.empty; + this.formats = new CSL.Stack(tokenstore); + this.current = new CSL.Stack(this.queue); }; -CSL.Engine.prototype.getDateNum = function (ItemField, partname) { - if ("undefined" === typeof ItemField) { - return 0; +CSL.Output.Queue.prototype.pop = function () { + var drip = this.current.value(); + if (drip.length) { + return drip.pop(); } else { - return ItemField[partname]; + return drip.blobs.pop(); } }; -CSL.Engine.getField = function (mode, hash, term, form, plural, gender) { - var ret, forms, f, pos, len, hashterm; - ret = ""; - if ("undefined" === typeof hash[term]) { - if (mode === CSL.STRICT) { - throw "Error in getField: term \"" + term + "\" does not exist."; - } else { - return undefined; +CSL.Output.Queue.prototype.getToken = function (name) { + var ret = this.formats.value()[name]; + return ret; +}; +CSL.Output.Queue.prototype.mergeTokenStrings = function (base, modifier) { + var base_token, modifier_token, ret, key; + base_token = this.formats.value()[base]; + modifier_token = this.formats.value()[modifier]; + ret = base_token; + if (modifier_token) { + if (!base_token) { + base_token = new CSL.Token(base, CSL.SINGLETON); + base_token.decorations = []; } - } - if (gender && hash[term][gender]) { - hashterm = hash[term][gender]; - } else { - hashterm = hash[term]; - } - forms = []; - if (form === "symbol") { - forms = ["symbol", "short"]; - } else if (form === "verb-short") { - forms = ["verb-short", "verb"]; - } else if (form !== "long") { - forms = [form]; - } - forms = forms.concat(["long"]); - len = forms.length; - for (pos = 0; pos < len; pos += 1) { - f = forms[pos]; - if ("string" === typeof hashterm || "number" === typeof hashterm) { - ret = hashterm; - } else if ("undefined" !== typeof hashterm[f]) { - if ("string" === typeof hashterm[f] || "number" === typeof hashterm[f]) { - ret = hashterm[f]; - } else { - if ("number" === typeof plural) { - ret = hashterm[f][plural]; - } else { - ret = hashterm[f][0]; - } + ret = new CSL.Token(base, CSL.SINGLETON); + key = ""; + for (key in base_token.strings) { + if (base_token.strings.hasOwnProperty(key)) { + ret.strings[key] = base_token.strings[key]; + } + } + for (key in modifier_token.strings) { + if (modifier_token.strings.hasOwnProperty(key)) { + ret.strings[key] = modifier_token.strings[key]; } - break; } + ret.decorations = base_token.decorations.concat(modifier_token.decorations); } return ret; }; -CSL.Engine.prototype.configureTokenLists = function () { - var dateparts_master, area, pos, token, dateparts, part, ppos, pppos, len, llen, lllen; - dateparts_master = ["year", "month", "day"]; - len = CSL.AREAS.length; - for (pos = 0; pos < len; pos += 1) { - area = CSL.AREAS[pos]; - llen = this[area].tokens.length - 1; - for (ppos = llen; ppos > -1; ppos += -1) { - token = this[area].tokens[ppos]; - if ("date" === token.name && CSL.END === token.tokentype) { - dateparts = []; - } - if ("date-part" === token.name && token.strings.name) { - lllen = dateparts_master.length; - for (pppos = 0; pppos < lllen; pppos += 1) { - part = dateparts_master[pppos]; - if (part === token.strings.name) { - dateparts.push(token.strings.name); - } - } - } - if ("date" === token.name && CSL.START === token.tokentype) { - dateparts.reverse(); - token.dateparts = dateparts; - } - token.next = (ppos + 1); - if (token.name && CSL.Node[token.name].configure) { - CSL.Node[token.name].configure.call(token, this, ppos); +CSL.Output.Queue.prototype.addToken = function (name, modifier, token) { + var newtok, attr; + newtok = new CSL.Token("output"); + if ("string" === typeof token) { + token = this.formats.value()[token]; + } + if (token && token.strings) { + for (attr in token.strings) { + if (token.strings.hasOwnProperty(attr)) { + newtok.strings[attr] = token.strings[attr]; } } + newtok.decorations = token.decorations; } - this.version = CSL.version; - return this.state; + if ("string" === typeof modifier) { + newtok.strings.delimiter = modifier; + } + this.formats.value()[name] = newtok; }; -CSL.Engine.prototype.retrieveItems = function (ids) { - var ret, pos, len; - ret = []; - for (var i = 0, ilen = ids.length; i < ilen; i += 1) { - ret.push(this.retrieveItem("" + ids[i])); +CSL.Output.Queue.prototype.pushFormats = function (tokenstore) { + if (!tokenstore) { + tokenstore = {}; } - return ret; + tokenstore.empty = this.empty; + this.formats.push(tokenstore); }; -CSL.ITERATION = 0; -CSL.Engine.prototype.retrieveItem = function (id) { - var Item, m, pos, len, mm; - if (this.opt.development_extensions.normalize_lang_keys_to_lowercase && - "boolean" === typeof this.opt.development_extensions.normalize_lang_keys_to_lowercase) { - for (var i=0,ilen=this.opt["default-locale"].length; i<ilen; i+=1) { - this.opt["default-locale"][i] = this.opt["default-locale"][i].toLowerCase(); - } - for (var i=0,ilen=this.opt["locale-translit"].length; i<ilen; i+=1) { - this.opt["locale-translit"][i] = this.opt["locale-translit"][i].toLowerCase(); - } - for (var i=0,ilen=this.opt["locale-translat"].length; i<ilen; i+=1) { - this.opt["locale-translat"][i] = this.opt["locale-translat"][i].toLowerCase(); - } - this.opt.development_extensions.normalize_lang_keys_to_lowercase = 100; +CSL.Output.Queue.prototype.popFormats = function (tokenstore) { + this.formats.pop(); +}; +CSL.Output.Queue.prototype.startTag = function (name, token) { + var tokenstore = {}; + if (this.state.tmp["doing-macro-with-date"] && this.state.tmp.extension) { + token = this.empty; + name = "empty"; } - CSL.ITERATION += 1; - Item = this.sys.retrieveItem("" + id); - if (this.opt.development_extensions.normalize_lang_keys_to_lowercase) { - if (Item.multi) { - if (Item.multi._keys) { - for (var field in Item.multi._keys) { - for (var key in Item.multi._keys[field]) { - if (key !== key.toLowerCase()) { - Item.multi._keys[field][key.toLowerCase()] = Item.multi._keys[field][key]; - delete Item.multi._keys[field][key]; - } - } - } - } - if (Item.multi.main) { - for (var field in Item.multi.main) { - Item.multi.main[field] = Item.multi.main[field].toLowerCase(); - } - } - } - for (var i=0, ilen=CSL.CREATORS.length; i>ilen; i+=1) { - var ctype = CSL.CREATORS[i]; - if (Item[ctype] && Item[ctype].multi) { - for (var j=0, jlen=Item[ctype].length; j<jlen; j+=1) { - var creator = Item[ctype][j]; - if (creator.multi) { - if (creator.multi._key) { - for (var key in creator.multi._key) { - if (key !== key.toLowerCase()) { - creator.multi._key[key.toLowerCase()] = creator.multi._key[key]; - delete creator.multi._key[key]; - } - } - } - if (creator.multi.main) { - creator.multi.main = creator.multi.main.toLowerCase(); - } - } - } - } + tokenstore[name] = token; + this.pushFormats(tokenstore); + this.openLevel(name); +}; +CSL.Output.Queue.prototype.endTag = function (name) { + this.closeLevel(); + this.popFormats(); +}; +CSL.Output.Queue.prototype.openLevel = function (token, ephemeral) { + var blob, curr, x, has_ephemeral; + if ("object" === typeof token) { + blob = new CSL.Blob(undefined, token); + } else if ("undefined" === typeof token) { + blob = new CSL.Blob(undefined, this.formats.value().empty, "empty"); + } else { + if (!this.formats.value() || !this.formats.value()[token]) { + throw "CSL processor error: call to nonexistent format token \"" + token + "\""; } + blob = new CSL.Blob(undefined, this.formats.value()[token], token); } - if (Item.page) { - Item["page-first"] = Item.page; - var num = "" + Item.page; - m = num.split(/\s*(?:&|,|-|\u2013)\s*/); - if (m[0].slice(-1) !== "\\") { - Item["page-first"] = m[0]; - } + if (this.nestedBraces) { + blob.strings.prefix = blob.strings.prefix.replace(this.nestedBraces[0][0], this.nestedBraces[0][1]); + blob.strings.prefix = blob.strings.prefix.replace(this.nestedBraces[1][0], this.nestedBraces[1][1]); + blob.strings.suffix = blob.strings.suffix.replace(this.nestedBraces[0][0], this.nestedBraces[0][1]); + blob.strings.suffix = blob.strings.suffix.replace(this.nestedBraces[1][0], this.nestedBraces[1][1]); } - if (this.opt.development_extensions.field_hack && Item.note) { - m = Item.note.match(CSL.NOTE_FIELDS_REGEXP); - if (m) { - var names = {}; - for (pos = 0, len = m.length; pos < len; pos += 1) { - mm = m[pos].match(CSL.NOTE_FIELD_REGEXP); - if (!Item[mm[1]] && CSL.DATE_VARIABLES.indexOf(mm[1]) > -1) { - Item[mm[1]] = {raw:mm[2]}; - } else if (!Item[mm[1]] && CSL.NAME_VARIABLES.indexOf(mm[1]) > -1) { - if (!Item[mm[1]]) { - Item[mm[1]] = []; - } - var lst = mm[2].split(/\s*\|\|\s*/); - if (lst.length === 1) { - Item[mm[1]].push({family:lst[0],isInstitution:true}); - } else if (lst.length === 2) { - Item[mm[1]].push({family:lst[0],given:lst[1]}); - } - } else if (!Item[mm[1]] || mm[1] === "type") { - Item[mm[1]] = mm[2].replace(/^\s+/, "").replace(/\s+$/, ""); - } - Item.note.replace(CSL.NOTE_FIELD_REGEXP, ""); - } - } + curr = this.current.value(); + curr.push(blob); + this.current.push(blob); +}; +CSL.Output.Queue.prototype.closeLevel = function (name) { + if (name && name !== this.current.value().levelname) { + CSL.error("Level mismatch error: wanted " + name + " but found " + this.current.value().levelname); } - for (var i = 1, ilen = CSL.DATE_VARIABLES.length; i < ilen; i += 1) { - var dateobj = Item[CSL.DATE_VARIABLES[i]]; - if (dateobj) { - if (this.opt.development_extensions.raw_date_parsing) { - if (dateobj.raw) { - dateobj = this.fun.dateparser.parse(dateobj.raw); - } - } - Item[CSL.DATE_VARIABLES[i]] = this.dateParseArray(dateobj); - } + this.current.pop(); +}; +CSL.Output.Queue.prototype.append = function (str, tokname, notSerious, ignorePredecessor, noStripPeriods) { + var token, blob, curr; + var useblob = true; + if (notSerious) { + ignorePredecessor = true; } - if (this.opt.development_extensions.static_statute_locator) { - if (Item.type && ["bill","gazette","legislation","treaty"].indexOf(Item.type) > -1) { - var varname; - var elements = ["type", "title", "jurisdiction", "genre", "volume", "container-title"]; - var legislation_id = []; - for (i = 0, ilen = elements.length; i < ilen; i += 1) { - varname = elements[i]; - if (Item[varname]) { - legislation_id.push(Item[varname]); - } - } - elements = ["original-date", "issued"]; - for (i = 0, elements.length; i < ilen; i += 1) { - varname = elements[i]; - if (Item[varname] && Item[varname].year) { - var value = Item[varname].year; - legislation_id.push(value); - break; - } - } - Item.legislation_id = legislation_id.join("::"); + if (this.state.tmp["doing-macro-with-date"]) { + if (tokname !== "macro-with-date") { + return false; } - } - if (this.opt.development_extensions.main_title_from_short_title) { - Item["title-main"] = Item.title; - Item["title-sub"] = false; - if (Item.title && Item.shortTitle) { - offset = Item.shortTitle.length; - if (Item.title.slice(0,offset) === Item.shortTitle && Item.title.slice(offset).match(/^\s*:/)) { - Item["title-main"] = Item.title.slice(0,offset).replace(/\s+$/,""); - Item["title-sub"] = Item.title.slice(offset).replace(/^\s*:\s*/,""); - } + if (tokname === "macro-with-date") { + tokname = "empty"; } } - if (!Item["title-short"]) { - Item["title-short"] = Item.shortTitle; + if ("undefined" === typeof str) { + return false; } - var isLegalType = ["legal_case","legislation","gazette","regulation"].indexOf(Item.type) > -1; - if (isLegalType) { - if (!Item["title-short"]) { - Item["title-short"] = Item.title; - } - } else if (Item.title && this.sys.getAbbreviation) { - var jurisdiction = this.transform.loadAbbreviation(Item.jurisdiction, "title", Item.title); - if (this.transform.abbrevs[jurisdiction].title) { - if (this.transform.abbrevs[jurisdiction].title[Item.title]) { - Item["title-short"] = this.transform.abbrevs[jurisdiction].title[Item.title]; - } - } + if ("number" === typeof str) { + str = "" + str; } - Item["container-title-short"] = Item.journalAbbreviation; - if (Item["container-title"] && this.sys.getAbbreviation) { - var jurisdiction = this.transform.loadAbbreviation(Item.jurisdiction, "title", Item["container-title"]); - if (this.transform.abbrevs[jurisdiction].title) { - if (this.transform.abbrevs[jurisdiction].title[Item["container-title"]]) { - Item["container-title-short"] = this.transform.abbrevs[jurisdiction].title[Item["container-title"]]; - } - } + if (!notSerious + && this.state.tmp.element_trace + && this.state.tmp.element_trace.value() === "suppress-me") { + return false; } - return Item; -}; -CSL.Engine.prototype.setOpt = function (token, name, value) { - if (token.name === "style" || token.name === "cslstyle") { - this.opt[name] = value; - } else if (["citation", "bibliography"].indexOf(token.name) > -1) { - this[token.name].opt[name] = value; - } else if (["name-form", "name-delimiter", "names-delimiter"].indexOf(name) === -1) { - token.strings[name] = value; + blob = false; + if (!tokname) { + token = this.formats.value().empty; + } else if (tokname === "literal") { + token = true; + useblob = false; + } else if ("string" === typeof tokname) { + token = this.formats.value()[tokname]; + } else { + token = tokname; } -}; -CSL.Engine.prototype.fixOpt = function (token, name, localname) { - if (["citation", "bibliography"].indexOf(token.name) > -1) { - if (! this[token.name].opt[name] && "undefined" !== typeof this.opt[name]) { - this[token.name].opt[name] = this.opt[name]; - } + if (!token) { + throw "CSL processor error: unknown format token name: " + tokname; } - if ("name" === token.name || "names" === token.name) { - if ("undefined" === typeof token.strings[localname] && "undefined" !== typeof this[this.build.root].opt[name]) { - token.strings[localname] = this[this.build.root].opt[name]; + if (token.strings && "undefined" === typeof token.strings.delimiter) { + token.strings.delimiter = ""; + } + if ("string" === typeof str && str.length) { + str = str.replace(/ ([:;?!\u00bb])/g, "\u202f$1").replace(/\u00ab /g, "\u00ab\u202f"); + this.last_char_rendered = str.slice(-1); + str = str.replace(/\s+'/g, " \'").replace(/^'/g, " \'"); + if (!ignorePredecessor) { + this.state.tmp.term_predecessor = true; + } else if (notSerious) { + this.state.tmp.term_predecessor_name = true; } } -}; -CSL.Engine.prototype.remapSectionVariable = function (inputList) { - for (var i = 0, ilen = inputList.length; i < ilen; i += 1) { - var Item = inputList[i][0]; - var item = inputList[i][1]; - var section_label_count = 0; - var later_label = false; - var value = false; - if (["bill","gazette","legislation","treaty"].indexOf(Item.type) > -1) { - item.force_pluralism = 0; - if (!item.label) { - item.label = "page" - } - var loci = ["section","","",""]; - var split; - if (this.opt.development_extensions.static_statute_locator && Item.section) { - splt = Item.section.replace(/^\s+/,"").replace(/\s+$/, "").split(/\s+/); - if (CSL.STATUTE_SUBDIV_STRINGS[splt[0]]) { - loci[0] = " " + splt[0] + " "; - loci[1] = splt.slice(1).join(" "); - } else { - loci[0] = " sec. "; - loci[1] = splt.slice(0).join(" "); - } - } else { - if (this.opt.development_extensions.clobber_locator_if_no_statute_section) { - item.locator = undefined; - item.label = undefined; - } + blob = new CSL.Blob(str, token); + if (this.nestedBraces) { + blob.strings.prefix = blob.strings.prefix.replace(this.nestedBraces[0][0], this.nestedBraces[0][1]); + blob.strings.prefix = blob.strings.prefix.replace(this.nestedBraces[1][0], this.nestedBraces[1][1]); + blob.strings.suffix = blob.strings.suffix.replace(this.nestedBraces[0][0], this.nestedBraces[0][1]); + blob.strings.suffix = blob.strings.suffix.replace(this.nestedBraces[1][0], this.nestedBraces[1][1]); + } + curr = this.current.value(); + if ("undefined" === typeof curr && this.current.mystack.length === 0) { + this.current.mystack.push([]); + curr = this.current.value(); + } + if ("string" === typeof blob.blobs) { + if (!ignorePredecessor) { + this.state.tmp.term_predecessor = true; + } else if (notSerious) { + this.state.tmp.term_predecessor_name = true; + } + } + if (!notSerious) { + this.state.parallel.AppendBlobPointer(curr); + } + if ("string" === typeof str) { + curr.push(blob); + if (blob.strings["text-case"]) { + blob.blobs = CSL.Output.Formatters[blob.strings["text-case"]](this.state, str); + } + if (this.state.tmp.strip_periods && !noStripPeriods) { + blob.blobs = blob.blobs.replace(/\.([^a-z]|$)/g, "$1"); + } + for (var i = blob.decorations.length - 1; i > -1; i += -1) { + if (blob.decorations[i][0] === "@quotes" && blob.decorations[i][1] === "true") { + blob.punctuation_in_quote = this.state.getOpt("punctuation-in-quote") } - if (item.locator) { - var splt = item.locator.replace(/^\s+/,"").replace(/\s+$/, "").split(/\s+/); - if (CSL.STATUTE_SUBDIV_STRINGS[splt[0]]) { - loci[2] = " " + splt[0] + " "; - loci[3] = splt.slice(1).join(" "); - } else if (item.label) { - loci[2] = " " + CSL.STATUTE_SUBDIV_STRINGS_REVERSE[item.label] + " "; - loci[3] = splt.slice(0).join(" "); - } else { - loci[3] = splt.join(" ") - } - if (loci[3] && loci[3].slice(0,1) === "&") { - loci[3] = " " + loci[3]; + if (!blob.blobs.match(CSL.ROMANESQUE_REGEXP)) { + if (blob.decorations[i][0] === "@font-style") { + blob.decorations = blob.decorations.slice(0, i).concat(blob.decorations.slice(i + 1)); } } - if (!loci[2]) { - loci[2] = loci[0]; - } - if (loci[3]) { - if (loci[3].match(/^[^0-9a-zA-Z]/)) { - var loclst = loci[3].split(/\s+/); - if (loci[0] === loci[2] && loclst[1] && !CSL.STATUTE_SUBDIV_STRINGS[loclst[1].replace(/\s+/, "").replace(/\s+/, "")]) { - item.force_pluralism = 1; + } + this.state.fun.flipflopper.init(str, blob); + this.state.fun.flipflopper.processTags(); + } else if (useblob) { + curr.push(blob); + } else { + curr.push(str); + } + return true; +}; +CSL.Output.Queue.prototype.string = function (state, myblobs, blob) { + var i, ilen, j, jlen, b; + var txt_esc = CSL.getSafeEscape(this.state); + var blobs = myblobs.slice(); + var ret = []; + if (blobs.length === 0) { + return ret; + } + var blob_delimiter = ""; + if (blob) { + blob_delimiter = blob.strings.delimiter; + } else { + state.tmp.count_offset_characters = false; + state.tmp.offset_characters = 0; + } + if (blob && blob.new_locale) { + blob.old_locale = state.opt.lang; + state.opt.lang = blob.new_locale; + } + var blobjr, use_suffix, use_prefix, params; + for (i = 0, ilen = blobs.length; i < ilen; i += 1) { + blobjr = blobs[i]; + if (blobjr.strings.first_blob) { + state.tmp.count_offset_characters = blobjr.strings.first_blob; + } + if ("string" === typeof blobjr.blobs) { + if ("number" === typeof blobjr.num) { + ret.push(blobjr); + } else if (blobjr.blobs) { + b = txt_esc(blobjr.blobs); + var blen = b.length; + if (!state.tmp.suppress_decorations) { + for (j = 0, jlen = blobjr.decorations.length; j < jlen; j += 1) { + params = blobjr.decorations[j]; + if (params[0] === "@showid") { + continue; + } + if (state.normalDecorIsOrphan(blobjr, params)) { + continue; + } + b = state.fun.decorate[params[0]][params[1]](state, b, params[2]); } - loci[2] = ""; } - } else { - loci[2] = ""; - } - if (!loci[1]) { - loci[0] = ""; - } - var value = loci.join(""); - value = value.replace(/^\s+/,"").replace(/\s+$/, ""); - if (value) { - splt = value.split(/\s+/); - if (CSL.STATUTE_SUBDIV_STRINGS[splt[0]]) { - var has_other = false; - for (var j = splt.length - 2; j > 0; j += -2) { - if (splt[j] === splt[0]) { - item.force_pluralism = 1; - splt = splt.slice(0,j).concat(splt.slice(j + 1)); + if (b && b.length) { + b = txt_esc(blobjr.strings.prefix, state.tmp.nestedBraces) + b + txt_esc(blobjr.strings.suffix, state.tmp.nestedBraces); + if (state.opt.development_extensions.csl_reverse_lookup_support && !state.tmp.suppress_decorations) { + for (j = 0, jlen = blobjr.decorations.length; j < jlen; j += 1) { + params = blobjr.decorations[j]; + if (params[0] === "@showid") { + b = state.fun.decorate[params[0]][params[1]](state, b, params[2]); + } } } - item.label = CSL.STATUTE_SUBDIV_STRINGS[splt[0]]; - item.locator = splt.slice(1).join(" "); - if (item.force_pluralism === 0) { - delete item.force_pluralism; + ret.push(b); + if (state.tmp.count_offset_characters) { + state.tmp.offset_characters += (blen + blobjr.strings.suffix.length + blobjr.strings.prefix.length); } - } else { - item.locator = splt.slice(0).join(" "); } } + } else if (blobjr.blobs.length) { + var addtoret = state.output.string(state, blobjr.blobs, blobjr); + ret = ret.concat(addtoret); + } + if (blobjr.strings.first_blob) { + state.registry.registry[blobjr.strings.first_blob].offset = state.tmp.offset_characters; + state.tmp.count_offset_characters = false; } } -} -CSL.Engine.prototype.setNumberLabels = function (Item) { - if (Item.number - && ["bill", "gazette", "legislation", "treaty"].indexOf(Item.type) > -1 - && this.opt.development_extensions.static_statute_locator - && !this.tmp.shadow_numbers["number"]) { - this.tmp.shadow_numbers["number"] = {}; - this.tmp.shadow_numbers["number"].values = []; - this.tmp.shadow_numbers["number"].plural = 0; - this.tmp.shadow_numbers["number"].numeric = false; - this.tmp.shadow_numbers["number"].label = false; - var value = "" + Item.number; - value = value.replace("\\", "", "g"); - var firstword = value.split(/\s/)[0]; - var firstlabel = CSL.STATUTE_SUBDIV_STRINGS[firstword]; - if (firstlabel) { - var m = value.match(CSL.STATUTE_SUBDIV_GROUPED_REGEX); - var splt = value.split(CSL.STATUTE_SUBDIV_PLAIN_REGEX); - if (splt.length > 1) { - var lst = []; - for (var j=1, jlen=splt.length; j < jlen; j += 1) { - var subdiv = m[j - 1].replace(/^\s*/, ""); - lst.push(subdiv.replace("sec.", "Sec.").replace("ch.", "Ch.")); - lst.push(splt[j].replace(/\s*$/, "").replace(/^\s*/, "")); + for (i=0,ilen=ret.length - 1;i<ilen;i+=1) { + if ("number" === typeof ret[i].num && "number" === typeof ret[i+1].num && !ret[i+1].UGLY_DELIMITER_SUPPRESS_HACK) { + ret[i].strings.suffix = txt_esc(blob_delimiter); + ret[i+1].successor_prefix = ""; + ret[i+1].UGLY_DELIMITER_SUPPRESS_HACK = true; + } + } + var span_split = 0; + for (i = 0, ilen = ret.length; i < ilen; i += 1) { + if ("string" === typeof ret[i]) { + span_split = (parseInt(i, 10) + 1); + if (i < ret.length - 1 && "object" === typeof ret[i + 1]) { + if (blob_delimiter && !ret[i + 1].UGLY_DELIMITER_SUPPRESS_HACK) { + ret[i] += txt_esc(blob_delimiter); } - value = lst.join(" "); - } else { - value = splt[0]; + ret[i + 1].UGLY_DELIMITER_SUPPRESS_HACK = true; } - this.tmp.shadow_numbers["number"].values.push(["Blob", value, false]); - this.tmp.shadow_numbers["number"].numeric = false; - } else { - this.tmp.shadow_numbers["number"].values.push(["Blob", value, false]); - this.tmp.shadow_numbers["number"].numeric = true; } } -} -CSL.substituteOne = function (template) { - return function (state, list) { - if (!list) { - return ""; - } else { - return template.replace("%%STRING%%", list); + if (blob && (blob.decorations.length || blob.strings.suffix || blob.strings.prefix)) { + span_split = ret.length; + } + var blobs_start = state.output.renderBlobs(ret.slice(0, span_split), blob_delimiter, true); + if (blobs_start && blob && (blob.decorations.length || blob.strings.suffix || blob.strings.prefix)) { + if (!state.tmp.suppress_decorations) { + for (i = 0, ilen = blob.decorations.length; i < ilen; i += 1) { + params = blob.decorations[i]; + if (["@cite","@bibliography", "@display", "@showid"].indexOf(params[0]) > -1) { + continue; + } + if (state.normalDecorIsOrphan(blobjr, params)) { + continue; + } + blobs_start = state.fun.decorate[params[0]][params[1]](state, blobs_start, params[2]); + } } - }; -}; -CSL.substituteTwo = function (template) { - return function (param) { - var template2 = template.replace("%%PARAM%%", param); - return function (state, list) { - if (!list) { - return ""; - } else { - return template2.replace("%%STRING%%", list); - } - }; - }; -}; -CSL.Mode = function (mode) { - var decorations, params, param, func, val, args; - decorations = {}; - params = CSL.Output.Formats[mode]; - for (param in params) { - if (true) { - if ("@" !== param.slice(0, 1)) { - decorations[param] = params[param]; - continue; - } - func = false; - val = params[param]; - args = param.split('/'); - if (typeof val === "string" && val.indexOf("%%STRING%%") > -1) { - if (val.indexOf("%%PARAM%%") > -1) { - func = CSL.substituteTwo(val); - } else { - func = CSL.substituteOne(val); - } - } else if (typeof val === "boolean" && !val) { - func = CSL.Output.Formatters.passthrough; - } else if (typeof val === "function") { - func = val; - } else { - throw "CSL.Compiler: Bad " + mode + " config entry for " + param + ": " + val; + b = blobs_start; + use_suffix = blob.strings.suffix; + if (b && b.length) { + use_prefix = blob.strings.prefix; + b = txt_esc(use_prefix, state.tmp.nestedBraces) + b + txt_esc(use_suffix, state.tmp.nestedBraces); + if (state.tmp.count_offset_characters) { + state.tmp.offset_characters += (use_prefix.length + use_suffix.length); } - if (args.length === 1) { - decorations[args[0]] = func; - } else if (args.length === 2) { - if (!decorations[args[0]]) { - decorations[args[0]] = {}; + } + blobs_start = b; + if (!state.tmp.suppress_decorations) { + for (i = 0, ilen = blob.decorations.length; i < ilen; i += 1) { + params = blob.decorations[i]; + if (["@cite","@bibliography", "@display", "@showid"].indexOf(params[0]) === -1) { + continue; } - decorations[args[0]][args[1]] = func; + blobs_start = state.fun.decorate[params[0]][params[1]].call(blob, state, blobs_start, params[2]); } } } - return decorations; -}; -CSL.setDecorations = function (state, attributes) { - var ret, key, pos; - ret = []; - for (pos in CSL.FORMAT_KEY_SEQUENCE) { - if (true) { - key = CSL.FORMAT_KEY_SEQUENCE[pos]; - if (attributes[key]) { - ret.push([key, attributes[key]]); - delete attributes[key]; - } + var blobs_end = ret.slice(span_split, ret.length); + if (!blobs_end.length && blobs_start) { + ret = [blobs_start]; + } else if (blobs_end.length && !blobs_start) { + ret = blobs_end; + } else if (blobs_start && blobs_end.length) { + ret = [blobs_start].concat(blobs_end); + } + if ("undefined" === typeof blob) { + this.queue = []; + this.current.mystack = []; + this.current.mystack.push(this.queue); + if (state.tmp.suppress_decorations) { + ret = state.output.renderBlobs(ret, undefined, true); } + } else if ("boolean" === typeof blob) { + ret = state.output.renderBlobs(ret, undefined, true); + } + if (blob && blob.new_locale) { + state.opt.lang = blob.old_locale; } return ret; }; -CSL.Engine.prototype.normalDecorIsOrphan = function (blob, params) { - if (params[1] === "normal") { - var use_param = false; - var all_the_decor; - if (this.tmp.area === "citation") { - all_the_decor = [this.citation.opt.layout_decorations].concat(blob.alldecor); +CSL.Output.Queue.prototype.clearlevel = function () { + var blob, pos, len; + blob = this.current.value(); + len = blob.blobs.length; + for (pos = 0; pos < len; pos += 1) { + blob.blobs.pop(); + } +}; +CSL.Output.Queue.prototype.renderBlobs = function (blobs, delim, in_cite) { + var state, ret, ret_last_char, use_delim, i, blob, pos, len, ppos, llen, pppos, lllen, res, str, params, txt_esc; + txt_esc = CSL.getSafeEscape(this.state); + if (!delim) { + delim = ""; + } + state = this.state; + ret = ""; + ret_last_char = []; + use_delim = ""; + len = blobs.length; + var start = true; + for (pos = 0; pos < len; pos += 1) { + if (blobs[pos].checkNext) { + blobs[pos].checkNext(blobs[(pos + 1)],start); + start = false; } else { - all_the_decor = blob.alldecor; + start = true; } - for (var k = all_the_decor.length - 1; k > -1; k += -1) { - for (var n = all_the_decor[k].length - 1; n > -1; n += -1) { - if (all_the_decor[k][n][0] === params[0]) { - if (all_the_decor[k][n][1] !== "normal") { - use_param = true; + } + var doit = true; + for (pos = blobs.length - 1; pos > 0; pos += -1) { + if (blobs[pos].checkLast) { + if (doit && blobs[pos].checkLast(blobs[pos - 1])) { + doit = false; + } + } else { + doit = true; + } + } + len = blobs.length; + for (pos = 0; pos < len; pos += 1) { + blob = blobs[pos]; + if (ret) { + use_delim = delim; + } + if (blob && "string" === typeof blob) { + ret += txt_esc(use_delim); + ret += blob; + if (state.tmp.count_offset_characters) { + state.tmp.offset_characters += (use_delim.length); + } + } else if (blob.status !== CSL.SUPPRESS) { + str = blob.formatter.format(blob.num, blob.gender); + var strlen = str.replace(/<[^>]*>/g, "").length; + this.append(str, "empty", true); + var str_blob = this.pop(); + var count_offset_characters = state.tmp.count_offset_characters; + str = this.string(state, [str_blob], false); + state.tmp.count_offset_characters = count_offset_characters; + if (blob.strings["text-case"]) { + str = CSL.Output.Formatters[blob.strings["text-case"]](this.state, str); + } + if (str && this.state.tmp.strip_periods) { + str = str.replace(/\.([^a-z]|$)/g, "$1"); + } + if (!state.tmp.suppress_decorations) { + llen = blob.decorations.length; + for (ppos = 0; ppos < llen; ppos += 1) { + params = blob.decorations[ppos]; + if (state.normalDecorIsOrphan(blob, params)) { + continue; } + str = state.fun.decorate[params[0]][params[1]](state, str, params[2]); } } - } - if (!use_param) { - return true; + str = txt_esc(blob.strings.prefix) + str + txt_esc(blob.strings.suffix); + var addme = ""; + if (blob.status === CSL.END) { + addme = txt_esc(blob.range_prefix); + } else if (blob.status === CSL.SUCCESSOR) { + addme = txt_esc(blob.successor_prefix); + } else if (blob.status === CSL.START) { + addme = ""; + } else if (blob.status === CSL.SEEN) { + addme = txt_esc(blob.splice_prefix); + } + ret += addme; + ret += str; + if (state.tmp.count_offset_characters) { + state.tmp.offset_characters += (addme.length + blob.strings.prefix.length + strlen + blob.strings.suffix.length); + } } } - return false; + return ret; }; -CSL.Engine.prototype.setOutputFormat = function (mode) { - this.opt.mode = mode; - this.fun.decorate = CSL.Mode(mode); - if (!this.output[mode]) { - this.output[mode] = {}; - this.output[mode].tmp = {}; +CSL.Output.Queue.purgeEmptyBlobs = function (myblobs, endOnly) { + var res, i, ilen, j, jlen, tmpblobs; + if ("string" === typeof myblobs || !myblobs.length) { + return; } -}; -CSL.Engine.prototype.setLangTagsForCslSort = function (tags) { - var i, ilen; - if (tags) { - this.opt['locale-sort'] = []; - for (i = 0, ilen = tags.length; i < ilen; i += 1) { - this.opt['locale-sort'].push(tags[i]); + for (i = myblobs.length - 1; i > -1; i += -1) { + CSL.Output.Queue.purgeEmptyBlobs(myblobs[i].blobs, endOnly); + } + for (i = myblobs.length - 1; i > -1; i += -1) { + if (!myblobs[i].blobs.length) { + tmpblobs = myblobs.slice(i + 1); + for (j = i, jlen = myblobs.length; j < jlen; j += 1) { + myblobs.pop(); + } + for (j = 0, jlen = tmpblobs.length; j < jlen; j += 1) { + myblobs.push(tmpblobs[j]); + } + } + if (endOnly) { + break; } } }; -CSL.Engine.prototype.setLangTagsForCslTransliteration = function (tags) { - var i, ilen; - this.opt['locale-translit'] = []; - if (tags) { - for (i = 0, ilen = tags.length; i < ilen; i += 1) { - this.opt['locale-translit'].push(tags[i]); +CSL.Output.Queue.purgeNearsidePrefixChars = function(myblob, chr) { + if (!chr) { + return; + } + if ("object" === typeof myblob) { + if ((CSL.TERMINAL_PUNCTUATION.indexOf(chr) > -1 + && CSL.TERMINAL_PUNCTUATION.slice(0, -1).indexOf(myblob.strings.prefix.slice(0, 1)) > -1) + && !(myblob.strings.prefix.slice(0,1) === ";" && chr === ".")) { + myblob.strings.prefix = myblob.strings.prefix.slice(1); + } else if ("object" === typeof myblob.blobs) { + CSL.Output.Queue.purgeNearsidePrefixChars(myblob.blobs[0], chr); } } }; -CSL.Engine.prototype.setLangTagsForCslTranslation = function (tags) { - var i, ilen; - this.opt['locale-translat'] = []; - if (tags) { - for (i = 0, ilen = tags.length; i < ilen; i += 1) { - this.opt['locale-translat'].push(tags[i]); +CSL.Output.Queue.purgeNearsidePrefixSpaces = function(myblob, chr) { + if ("object" === typeof myblob) { + if (" " === chr && " " === myblob.strings.prefix.slice(0, 1)) { + myblob.strings.prefix = myblob.strings.prefix.slice(1); + } else if ("object" === typeof myblob.blobs) { + CSL.Output.Queue.purgeNearsidePrefixSpaces(myblob.blobs[0], chr); } } }; -CSL.Engine.prototype.setLangPrefsForCites = function (obj, conv) { - var opt = this.opt['cite-lang-prefs']; - if (!conv) { - conv = function (key) { - return key.toLowerCase(); - }; - } - var segments = ['Persons', 'Institutions', 'Titles', 'Publishers', 'Places']; - for (var i = 0, ilen = segments.length; i < ilen; i += 1) { - var clientSegment = conv(segments[i]); - var citeprocSegment = segments[i].toLowerCase(); - if (!obj[clientSegment]) { - continue; +CSL.Output.Queue.purgeNearsideSuffixSpaces = function(myblob, chr) { + if ("object" === typeof myblob) { + if (" " === chr && " " === myblob.strings.suffix.slice(-1)) { + myblob.strings.suffix = myblob.strings.suffix.slice(0, -1); + } else if ("object" === typeof myblob.blobs) { + if (!chr) { + chr = myblob.strings.suffix.slice(-1); + } + chr = CSL.Output.Queue.purgeNearsideSuffixSpaces(myblob.blobs[myblob.blobs.length - 1], chr); + } else { + chr = myblob.strings.suffix.slice(-1); } - var supplements = []; - while (obj[clientSegment].length > 1) { - supplements.push(obj[clientSegment].pop()); + } + return chr; +}; +CSL.Output.Queue.adjustPunctuation = function (state, myblobs, stk) { + var chr, suffix, dpref, blob, delimiter, suffixX, dprefX, blobX, delimiterX, prefix, prefixX, dsuffX, dsuff, slast, dsufff, dsufffX, lastchr, firstchr, exposed_suffixes, exposed, j, jlen, i, ilen; + var TERMS = CSL.TERMINAL_PUNCTUATION.slice(0, -1); + var TERM_OR_SPACE = CSL.TERMINAL_PUNCTUATION; + var SWAPS = CSL.SWAPPING_PUNCTUATION; + if (!stk) { + stk = [{suffix: "", delimiter: "", lastNode:true}]; + } + slast = stk.length - 1; + delimiter = stk[slast].delimiter; + dpref = stk[slast].dpref; + dsuff = stk[slast].dsuff; + dsufff = stk[slast].dsufff; + prefix = stk[slast].prefix; + suffix = stk[slast].suffix; + blob = stk[slast].blob; + if ("string" === typeof myblobs) { + if (suffix) { + if (blob && + TERMS.indexOf(myblobs.slice(-1)) > -1 && + TERMS.slice(1).indexOf(suffix) > -1 && + blob.strings.suffix !== " ") { + blob.strings.suffix = blob.strings.suffix.slice(1); + } } - var sortval = {orig:1,translit:2,translat:3}; - if (supplements.length === 2 && sortval[supplements[0]] < sortval[supplements[1]]) { - supplements.reverse(); + lastchr = myblobs.slice(-1); + firstchr = myblobs.slice(0,1); + } else { + if (dpref) { + for (j = 0, jlen = myblobs.length - 1; j < jlen; j += 1) { + var t = myblobs[j].strings.suffix.slice(-1); + if (TERMS.indexOf(t) === -1 || + TERMS.indexOf(dpref) === -1) { + if (dpref !== " " || dpref !== myblobs[j].strings.suffix.slice(-1)) { + myblobs[j].strings.suffix += dpref; + } + } + } } - while (supplements.length) { - obj[clientSegment].push(supplements.pop()); + if (suffix === " ") { + CSL.Output.Queue.purgeNearsideSuffixSpaces(myblobs[myblobs.length - 1], " "); } - var lst = opt[citeprocSegment]; - while (lst.length) { - lst.pop(); + var lst = []; + var doblob; + for (i = 0, ilen = myblobs.length - 1; i < ilen; i += 1) { + doblob = myblobs[i]; + var following_prefix = myblobs[i + 1].strings.prefix; + chr = false; + var ret = CSL.Output.Queue.purgeNearsideSuffixSpaces(doblob, chr); + if (!dsuff) { + lst.push(ret); + } else { + lst.push(false); + } } - for (var j = 0, jlen = obj[clientSegment].length; j < jlen; j += 1) { - lst.push(obj[clientSegment][j]); + chr = false; + for (i = 1, ilen = myblobs.length; i < ilen; i += 1) { + doblob = myblobs[i]; + chr = ""; + var preceding_suffix = myblobs[i - 1].strings.suffix; + if (dsuff === " ") { + chr = dsuff; + } else if (preceding_suffix) { + chr = preceding_suffix.slice(-1); + } else if (lst[i - 1]) { + chr = lst[i - 1]; + } + CSL.Output.Queue.purgeNearsidePrefixSpaces(doblob, chr); } - } -}; -CSL.Engine.prototype.setLangPrefsForCiteAffixes = function (affixList) { - if (affixList && affixList.length === 40) { - var affixes = this.opt.citeAffixes; - var count = 0; - var settings = ["persons", "institutions", "titles", "publishers", "places"]; - var forms = ["translit", "orig", "translit", "translat"]; - var value; - for (var i = 0, ilen = settings.length; i < ilen; i += 1) { - for (var j = 0, jlen = forms.length; j < jlen; j += 1) { - value = ""; - if ((count % 8) === 4) { - if (!affixes[settings[i]]["locale-"+forms[j]].prefix - && !affixes[settings[i]]["locale-"+forms[j]].suffix) { - value = affixList[count] ? affixList[count] : ""; - affixes[settings[i]]["locale-" + forms[j]].prefix = value; - value = affixList[count] ? affixList[count + 1] : ""; - affixes[settings[i]]["locale-" + forms[j]].suffix = value; + if (dsufff) { + CSL.Output.Queue.purgeNearsidePrefixSpaces(myblobs[0], " "); + } else if (prefix === " ") { + CSL.Output.Queue.purgeNearsidePrefixSpaces(myblobs[0], " "); + } + for (i = 0, ilen = myblobs.length; i < ilen; i += 1) { + doblob = myblobs[i]; + CSL.Output.Queue.purgeNearsidePrefixChars(doblob, lastchr); + if (i === 0) { + if (prefix) { + if (doblob.strings.prefix.slice(0, 1) === " ") { } - } else { - value = affixList[count] ? affixList[count] : ""; - affixes[settings[i]]["locale-" + forms[j]].prefix = value; - value = affixList[count] ? affixList[count + 1] : ""; - affixes[settings[i]]["locale-" + forms[j]].suffix = value; } - count += 2; - } - } - this.opt.citeAffixes = affixes; - } -}; -CSL.Engine.prototype.setAutoVietnameseNamesOption = function (arg) { - if (arg) { - this.opt["auto-vietnamese-names"] = true; - } else { - this.opt["auto-vietnamese-names"] = false; - } -}; -CSL.Engine.prototype.setAbbreviations = function (arg) { - if (this.sys.setAbbreviations) { - this.sys.setAbbreviations(arg); - } -}; -CSL.Engine.Opt = function () { - this.has_disambiguate = false; - this.mode = "html"; - this.dates = {}; - this["locale-sort"] = []; - this["locale-translit"] = []; - this["locale-translat"] = []; - this.citeAffixes = { - persons:{ - "locale-orig":{ - prefix:"", - suffix:"" - }, - "locale-translit":{ - prefix:"", - suffix:"" - }, - "locale-translat":{ - prefix:"", - suffix:"" } - }, - institutions:{ - "locale-orig":{ - prefix:"", - suffix:"" - }, - "locale-translit":{ - prefix:"", - suffix:"" - }, - "locale-translat":{ - prefix:"", - suffix:"" + if (dsufff) { + if (doblob.strings.prefix) { + if (i === 0) { + if (doblob.strings.prefix.slice(0, 1) === " ") { + } + } + } } - }, - titles:{ - "locale-orig":{ - prefix:"", - suffix:"" - }, - "locale-translit":{ - prefix:"", - suffix:"" - }, - "locale-translat":{ - prefix:"", - suffix:"" + if (dsuff) { + if (i > 0) { + if (doblob.strings.prefix.slice(0, 1) === " ") { + } + } } - }, - publishers:{ - "locale-orig":{ - prefix:"", - suffix:"" - }, - "locale-translit":{ - prefix:"", - suffix:"" - }, - "locale-translat":{ - prefix:"", - suffix:"" + if (i < (myblobs.length - 1)) { + var nextprefix = myblobs[i + 1].strings.prefix; + if (!delimiter) { + if (nextprefix) { + var nxtchr = nextprefix.slice(0, 1); + if (SWAPS.indexOf(nxtchr) > -1) { + myblobs[i + 1].strings.prefix = nextprefix.slice(1); + if (TERMS.indexOf(nxtchr) === -1 || + (TERMS.indexOf(nxtchr) > -1 && + TERMS.indexOf(doblob.strings.suffix.slice(-1)) === -1)) { + doblob.strings.suffix += nxtchr; + } + } else if (nxtchr === " " && + doblob.strings.suffix.slice(-1) === " ") { + doblob.strings.suffix = doblob.strings.suffix.slice(0, -1); + } + } + } } - }, - places:{ - "locale-orig":{ - prefix:"", - suffix:"" - }, - "locale-translit":{ - prefix:"", - suffix:"" - }, - "locale-translat":{ - prefix:"", - suffix:"" + if (i === (myblobs.length - 1)) { + if (suffix) { + if (doblob.strings.suffix && + (TERMS.slice(1).indexOf(suffix) > -1 && + TERMS.indexOf(doblob.strings.suffix.slice(-1)) > -1)) { + blob.strings.suffix = blob.strings.suffix.slice(1); + } + } + } + if (state.getOpt('punctuation-in-quote')) { + var decorations = doblob.decorations; + for (j = 0, jlen = decorations.length; j < jlen; j += 1) { + if (decorations[j][0] === '@quotes' && decorations[j][1] === 'true') { + doblob.punctuation_in_quote = true; + stk[slast].lastNode = true; + } + } + } + if (doblob.punctuation_in_quote && stk[slast].lastNode) { + var swapchar = doblob.strings.suffix.slice(0, 1); + var swapblob = false; + if (SWAPS.indexOf(swapchar) > -1) { + swapblob = doblob; + } else if (SWAPS.indexOf(suffix) > -1 && i === (myblobs.length - 1)) { + swapchar = suffix; + swapblob = blob; + } else { + swapchar = false; + } + if (swapchar) { + if ("string" === typeof doblob.blobs) { + if (SWAPS.indexOf(doblob.blobs.slice(-1)) === -1 || + (TERMS.indexOf(doblob.blobs.slice(-1)) > -1 && + SWAPS.indexOf(swapchar) > -1 && + TERMS.indexOf(swapchar) === -1)) { + doblob.blobs += swapchar; + } + } else { + if (SWAPS.indexOf(doblob.blobs.slice(-1)[0].strings.suffix.slice(-1)) === -1 || + (TERMS.indexOf(doblob.blobs.slice(-1)[0].strings.suffix.slice(-1)) > -1 && + SWAPS.indexOf(swapchar) > -1 && + TERMS.indexOf(swapchar) === -1)) { + doblob.blobs.slice(-1)[0].strings.suffix += swapchar; + } + } + swapblob.strings.suffix = swapblob.strings.suffix.slice(1); + } + } + if (i === (myblobs.length - 1)) { + if (doblob.strings.suffix) { + suffixX = doblob.strings.suffix.slice(0, 1); + blobX = doblob; + } else { + suffixX = stk[stk.length - 1].suffix; + blobX = stk[stk.length - 1].blob; + } + } else { + if (doblob.strings.suffix) { + suffixX = doblob.strings.suffix.slice(0, 1); + blobX = doblob; + } else { + suffixX = ""; + blobX = false; + } + } + if (SWAPS.concat([" "]).indexOf(suffixX) === -1) { + suffixX = ""; + blobX = false; + } + if (doblob.strings.delimiter && + doblob.blobs.length > 1) { + dprefX = doblob.strings.delimiter.slice(0, 1); + if (SWAPS.concat([" "]).indexOf(dprefX) > -1) { + doblob.strings.delimiter = doblob.strings.delimiter.slice(1); + } else { + dprefX = ""; + } + } else { + dprefX = ""; + } + if (doblob.strings.prefix) { + if (doblob.strings.prefix.slice(-1) === " ") { + prefixX = " "; + } else { + prefixX = ""; + } + } else { + if (i === 0) { + prefixX = prefix; + } else { + prefixX = ""; + } + } + if (dsuff) { + dsufffX = dsuff; + } else { + if (i === 0) { + dsufffX = dsufff; + } else { + dsufffX = ""; + } + } + if (doblob.strings.delimiter) { + if (doblob.strings.delimiter.slice(-1) === " " && + "object" === typeof doblob.blobs && doblob.blobs.length > 1) { + dsuffX = doblob.strings.delimiter.slice(-1); + } else { + dsuffX = ""; + } + } else { + dsuffX = ""; + } + delimiterX = doblob.strings.delimiter; + var lastNode + if (i === (myblobs.length - 1) && stk[slast].lastNode) { + lastNode = true; + } else { + lastNode = false; + } + stk.push({suffix: suffixX, dsuff:dsuffX, blob:blobX, delimiter:delimiterX, prefix:prefixX, dpref: dprefX, dsufff: dsufffX, lastNode: lastNode}); + lastchr = CSL.Output.Queue.adjustPunctuation(state, doblob.blobs, stk); + } + if (myblobs && myblobs.length) { + var last_suffix = myblobs[myblobs.length - 1].strings.suffix; + if (last_suffix) { + lastchr = last_suffix.slice(-1); + } + } + } + if (stk.length > 1) { + stk.pop(); + } + state.tmp.last_chr = lastchr; + return lastchr; +}; +CSL.Engine.Opt = function () { + this.has_disambiguate = false; + this.mode = "html"; + this.dates = {}; + this["locale-sort"] = []; + this["locale-translit"] = []; + this["locale-translat"] = []; + this.citeAffixes = { + persons:{ + "locale-orig":{ + prefix:"", + suffix:"" + }, + "locale-translit":{ + prefix:"", + suffix:"" + }, + "locale-translat":{ + prefix:"", + suffix:"" + } + }, + institutions:{ + "locale-orig":{ + prefix:"", + suffix:"" + }, + "locale-translit":{ + prefix:"", + suffix:"" + }, + "locale-translat":{ + prefix:"", + suffix:"" + } + }, + titles:{ + "locale-orig":{ + prefix:"", + suffix:"" + }, + "locale-translit":{ + prefix:"", + suffix:"" + }, + "locale-translat":{ + prefix:"", + suffix:"" + } + }, + publishers:{ + "locale-orig":{ + prefix:"", + suffix:"" + }, + "locale-translit":{ + prefix:"", + suffix:"" + }, + "locale-translat":{ + prefix:"", + suffix:"" + } + }, + places:{ + "locale-orig":{ + prefix:"", + suffix:"" + }, + "locale-translit":{ + prefix:"", + suffix:"" + }, + "locale-translat":{ + prefix:"", + suffix:"" } } }; @@ -3400,517 +3499,8 @@ CSL.Engine.CitationSort = function () { this.tokens = []; this.opt = {}; this.opt.sort_directions = []; - this.keys = []; - this.opt.topdecor = []; -}; -CSL.Engine.prototype.setCitationId = function (citation, force) { - var ret, id, direction; - ret = false; - if (!citation.citationID || force) { - id = Math.floor(Math.random() * 100000000000000); - while (true) { - direction = 0; - if (!this.registry.citationreg.citationById[id]) { - citation.citationID = id.toString(32); - break; - } else if (!direction && id < 50000000000000) { - direction = 1; - } else { - direction = -1; - } - if (direction === 1) { - id += 1; - } else { - id += -1; - } - } - ret = "" + id; - } - this.registry.citationreg.citationById[citation.citationID] = citation; - return ret; -}; -CSL.Engine.prototype.rebuildProcessorState = function (citations, mode, uncitedItemIDs) { - if (!citations) { - citations = []; - } - if (!mode) { - mode = 'html'; - } - var itemIDs = []; - for (var i=0,ilen=citations.length;i<ilen;i+=1) { - for (var j=0,jlen=citations[i].citationItems.length;j<jlen;j+=1) { - var itemID = "" + citations[i].citationItems[j].id; - itemIDs.push(itemID); - } - } - this.updateItems(itemIDs); - var pre = []; - var post = []; - var ret = []; - var oldMode = this.opt.mode; - this.setOutputFormat(mode); - for (var i=0,ilen=citations.length;i<ilen;i+=1) { - var res = this.processCitationCluster(citations[i],pre,post,CSL.ASSUME_ALL_ITEMS_REGISTERED); - pre.push([citations[i].citationID,citations[i].properties.noteIndex]); - for (var j=0,jlen=res[1].length;j<jlen;j+=1) { - var index = res[1][j][0]; - ret[index] = [ - pre[index][0], - pre[index][1], - res[1][j][1] - ]; - } - } - this.updateUncitedItems(uncitedItemIDs); - this.setOutputFormat(oldMode); - return ret; -} -CSL.Engine.prototype.restoreProcessorState = function (citations) { - var i, ilen, j, jlen, item, Item, newitem, citationList, itemList, sortedItems; - citationList = []; - itemList = []; - if (!citations) { - citations = []; - } - var indexNumbers = []; - var citationIds = {}; - for (i = 0, ilen = citations.length; i < ilen; i += 1) { - if (citationIds[citations[i].citationID]) { - this.setCitationId(citations[i], true); - } - citationIds[citations[i].citationID] = true; - indexNumbers.push(citations[i].properties.index); - } - var oldCitations = citations.slice(); - oldCitations.sort( - function (a,b) { - if (a.properties.index < b.properties.index) { - return -1; - } else if (a.properties.index > b.properties.index) { - return 1; - } else { - return 0; - } - } - ); - for (i = 0, ilen = oldCitations.length; i < ilen; i += 1) { - oldCitations[i].properties.index = i; - } - for (i = 0, ilen = oldCitations.length; i < ilen; i += 1) { - sortedItems = []; - for (j = 0, jlen = oldCitations[i].citationItems.length; j < jlen; j += 1) { - item = oldCitations[i].citationItems[j]; - if ("undefined" === typeof item.sortkeys) { - item.sortkeys = []; - } - Item = this.retrieveItem("" + item.id); - newitem = [Item, item]; - sortedItems.push(newitem); - oldCitations[i].citationItems[j].item = Item; - itemList.push("" + item.id); - } - if (!oldCitations[i].properties.unsorted) { - sortedItems.sort(this.citation.srt.compareCompositeKeys); - } - oldCitations[i].sortedItems = sortedItems; - this.registry.citationreg.citationById[oldCitations[i].citationID] = oldCitations[i]; - } - this.updateItems(itemList); - for (i = 0, ilen = citations.length; i < ilen; i += 1) { - citationList.push(["" + citations[i].citationID, citations[i].properties.noteIndex]); - } - var ret = []; - if (citations && citations.length) { - ret = this.processCitationCluster(citations[0], [], citationList.slice(1)); - } else { - this.registry = new CSL.Registry(this); - this.tmp = new CSL.Engine.Tmp(); - this.disambiguate = new CSL.Disambiguation(this); - } - return ret; -}; -CSL.Engine.prototype.updateItems = function (idList, nosort, rerun_ambigs) { - var debug = false; - var oldArea = this.tmp.area; - this.registry.init(idList); - if (rerun_ambigs) { - for (var ambig in this.registry.ambigcites) { - this.registry.ambigsTouched[ambig] = true; - } - } - this.registry.dodeletes(this.registry.myhash); - this.registry.doinserts(this.registry.mylist); - this.registry.dorefreshes(); - this.registry.rebuildlist(); - this.registry.setsortkeys(); - this.registry.setdisambigs(); - if (!nosort) { - this.registry.sorttokens(); - } - this.registry.renumber(); - this.tmp.area = oldArea; - return this.registry.getSortedIds(); -}; -CSL.Engine.prototype.updateUncitedItems = function (idList, nosort) { - var debug = false; - if (!idList) { - idList = []; - } - if ("object" == typeof idList) { - if ("undefined" == typeof idList.length) { - var idHash = idList; - idList = []; - for (var key in idHash) { - idList.push(key); - } - } else if ("number" == typeof idList.length) { - var idHash = {}; - for (var i=0,ilen=idList.length;i<ilen;i+=1) { - idHash[idList[i]] = true; - } - } - } - this.registry.init(idList, true); - this.registry.dopurge(idHash); - this.registry.doinserts(this.registry.mylist); - this.registry.dorefreshes(); - this.registry.rebuildlist(); - this.registry.setsortkeys(); - this.registry.setdisambigs(); - if (!nosort) { - this.registry.sorttokens(); - } - this.registry.renumber(); - return this.registry.getSortedIds(); -}; -CSL.Engine.prototype.getCitationLabel = function (Item) { - var label = ""; - var params = this.getTrigraphParams(); - var config = params[0]; - var myname = this.getTerm("reference", "short", 0); - if ("undefined" === typeof myname) { - myname = "reference"; - } - myname = myname.replace(".", ""); - myname = myname.slice(0, 1).toUpperCase() + myname.slice(1); - for (var i = 0, ilen = CSL.CREATORS.length; i < ilen; i += 1) { - var n = CSL.CREATORS[i]; - if (Item[n]) { - var names = Item[n]; - if (names.length > params.length) { - config = params[params.length - 1]; - } else { - config = params[names.length - 1]; - } - for (var j = 0, jlen = names.length; j < jlen; j += 1) { - if (j === config.authors.length) { - break; - } - var res = this.nameOutput.getName(names[j], "locale-translit", true); - var name = res.name; - if (name && name.family) { - myname = name.family; - myname = myname.replace(/^([ \'\u2019a-z]+\s+)/, ""); - } else if (name && name.literal) { - myname = name.literal; - } - var m = myname.toLowerCase().match(/^(a\s+|the\s+|an\s+)/); - if (m) { - myname = myname.slice(m[1].length); - } - myname = myname.replace(CSL.ROMANESQUE_NOT_REGEXP, "", "g"); - if (!myname) { - break; - } - myname = myname.slice(0, config.authors[j]); - if (myname.length > 1) { - myname = myname.slice(0, 1).toUpperCase() + myname.slice(1).toLowerCase(); - } else if (myname.length === 1) { - myname = myname.toUpperCase(); - } - label += myname; - } - break; - } - } - var year = "0000"; - if (Item.issued) { - if (Item.issued.year) { - year = "" + Item.issued.year; - } - } - year = year.slice((config.year * -1)); - label = label + year; - return label; -}; -CSL.Engine.prototype.getTrigraphParams = function () { - var params = []; - var ilst = this.opt.trigraph.split(":"); - if (!this.opt.trigraph || this.opt.trigraph.slice(0,1) !== "A") { - throw "Bad trigraph definition: "+this.opt.trigraph; - } - for (var i = 0, ilen = ilst.length; i < ilen; i += 1) { - var str = ilst[i]; - var config = {authors:[], year:0}; - for (var j = 0, jlen = str.length; j < jlen; j += 1) { - switch (str.slice(j,j+1)) { - case "A": - config.authors.push(1); - break; - case "a": - config.authors[config.authors.length - 1] += 1; - break; - case "0": - config.year += 1; - break; - default: - throw "Invalid character in trigraph definition: "+this.opt.trigraph; - } - } - params.push(config); - } - return params; -}; -CSL.Engine.prototype.makeBibliography = function (bibsection) { - var debug, ret, params, maxoffset, item, len, pos, tok, tokk, tokkk, entry_ids, entry_strings, bibliography_errors; - debug = false; - if (!this.bibliography.tokens.length) { - return false; - } - if ("string" === typeof bibsection) { - this.opt.citation_number_slug = bibsection; - bibsection = false; - } - ret = CSL.getBibliographyEntries.call(this, bibsection); - entry_ids = ret[0]; - entry_strings = ret[1]; - var done = ret[2]; - params = { - "maxoffset": 0, - "entryspacing": this.bibliography.opt["entry-spacing"], - "linespacing": this.bibliography.opt["line-spacing"], - "second-field-align": false, - "entry_ids": entry_ids, - "bibliography_errors": this.tmp.bibliography_errors.slice(), - "done": done - }; - if (this.bibliography.opt["second-field-align"]) { - params["second-field-align"] = this.bibliography.opt["second-field-align"]; - } - maxoffset = 0; - len = this.registry.reflist.length; - for (pos = 0; pos < len; pos += 1) { - item = this.registry.reflist[pos]; - if (item.offset > params.maxoffset) { - params.maxoffset = item.offset; - } - } - if (this.bibliography.opt.hangingindent) { - params.hangingindent = this.bibliography.opt.hangingindent; - } - params.bibstart = this.fun.decorate.bibstart; - params.bibend = this.fun.decorate.bibend; - this.opt.citation_number_slug = false; - return [params, entry_strings]; -}; -CSL.getBibliographyEntries = function (bibsection) { - var ret, input, include, anymatch, allmatch, bib_entry, res, len, pos, item, llen, ppos, spec, lllen, pppos, bib_layout, topblobs, all_item_ids, entry_item_ids, debug, collapse_parallel, i, ilen, siblings, skips, sortedItems, eyetem, chr, entry_item_data, j, jlen, newIDs, originalIDs; - ret = []; - entry_item_data = []; - this.tmp.area = "bibliography"; - this.tmp.last_rendered_name = false; - this.tmp.bibliography_errors = []; - this.tmp.bibliography_pos = 0; - if (bibsection && bibsection.page_start && bibsection.page_length) { - input = this.registry.getSortedIds(); - } else { - input = this.retrieveItems(this.registry.getSortedIds()); - } - this.tmp.disambig_override = true; - function eval_string(a, b) { - if (a === b) { - return true; - } - return false; - } - function eval_list(a, lst) { - lllen = lst.length; - for (pppos = 0; pppos < lllen; pppos += 1) { - if (eval_string(a, lst[pppos])) { - return true; - } - } - return false; - } - function eval_spec(a, b) { - if ((a === "none" || !a) && !b) { - return true; - } - if ("string" === typeof b) { - return eval_string(a, b); - } else if (!b) { - return false; - } else { - return eval_list(a, b); - } - } - skips = {}; - var page_item_count; - if (bibsection && bibsection.page_start && bibsection.page_length) { - page_item_count = 0; - if (bibsection.page_start !== true) { - for (i = 0, ilen = input.length; i < ilen; i += 1) { - skips[input[i]] = true; - if (bibsection.page_start == input[i]) { - break; - } - } - } - } - var processed_item_ids = []; - for (i = 0, ilen = input.length; i < ilen; i += 1) { - if (bibsection && bibsection.page_start && bibsection.page_length) { - if (skips[input[i]]) { - continue; - } - item = this.retrieveItem(input[i]); - if (page_item_count === bibsection.page_length) { - break; - } - } else { - item = input[i]; - if (skips[item.id]) { - continue; - } - } - if (bibsection) { - include = true; - if (bibsection.include) { - include = false; - for (j = 0, jlen = bibsection.include.length; j < jlen; j += 1) { - spec = bibsection.include[j]; - if (eval_spec(spec.value, item[spec.field])) { - include = true; - break; - } - } - } else if (bibsection.exclude) { - anymatch = false; - for (j = 0, jlen = bibsection.exclude.length; j < jlen; j += 1) { - spec = bibsection.exclude[j]; - if (eval_spec(spec.value, item[spec.field])) { - anymatch = true; - break; - } - } - if (anymatch) { - include = false; - } - } else if (bibsection.select) { - include = false; - allmatch = true; - for (j = 0, jlen = bibsection.select.length; j < jlen; j += 1) { - spec = bibsection.select[j]; - if (!eval_spec(spec.value, item[spec.field])) { - allmatch = false; - } - } - if (allmatch) { - include = true; - } - } - if (bibsection.quash) { - allmatch = true; - for (j = 0, jlen = bibsection.quash.length; j < jlen; j += 1) { - spec = bibsection.quash[j]; - if (!eval_spec(spec.value, item[spec.field])) { - allmatch = false; - } - } - if (allmatch) { - include = false; - } - } - if (!include) { - continue; - } - } - bib_entry = new CSL.Token("group", CSL.START); - bib_entry.decorations = [["@bibliography", "entry"]].concat(this.bibliography.opt.layout_decorations); - this.output.startTag("bib_entry", bib_entry); - if (item.system_id && this.sys.embedBibliographyEntry) { - this.output.current.value().item_id = item.system_id; - } else { - this.output.current.value().system_id = item.id; - } - sortedItems = [[{id: "" + item.id}, item]]; - entry_item_ids = []; - if (this.registry.registry[item.id].master - && !(bibsection && bibsection.page_start && bibsection.page_length)) { - collapse_parallel = true; - this.parallel.StartCitation(sortedItems); - this.output.queue[0].strings.delimiter = ", "; - this.tmp.term_predecessor = false; - entry_item_ids.push("" + CSL.getCite.call(this, item)); - skips[item.id] = true; - siblings = this.registry.registry[item.id].siblings; - for (j = 0, jlen = siblings.length; j < jlen; j += 1) { - var k = this.registry.registry[item.id].siblings[j]; - eyetem = this.retrieveItem(k); - entry_item_ids.push("" + CSL.getCite.call(this, eyetem)); - skips[eyetem.id] = true; - } - this.parallel.ComposeSet(); - this.parallel.PruneOutputQueue(); - } else if (!this.registry.registry[item.id].siblings) { - this.parallel.StartCitation(sortedItems); - this.tmp.term_predecessor = false; - entry_item_ids.push("" + CSL.getCite.call(this, item)); - if (bibsection && bibsection.page_start && bibsection.page_length) { - page_item_count += 1; - } - } - entry_item_data.push(""); - this.tmp.bibliography_pos += 1; - processed_item_ids.push(entry_item_ids); - this.output.endTag("bib_entry"); - if (this.output.queue[0].blobs.length && this.output.queue[0].blobs[0].blobs.length) { - if (collapse_parallel || !this.output.queue[0].blobs[0].blobs[0].strings) { - topblobs = this.output.queue[0].blobs; - collapse_parallel = false; - } else { - topblobs = this.output.queue[0].blobs[0].blobs; - } - for (j = topblobs.length - 1; j > -1; j += -1) { - if (topblobs[j].blobs && topblobs[j].blobs.length !== 0) { - chr = this.bibliography.opt.layout_suffix.slice(0, 1); - if (chr && topblobs[j].strings.suffix.slice(-1) === chr) { - topblobs[j].strings.suffix = topblobs[j].strings.suffix.slice(0, -1); - } - topblobs[j].strings.suffix += this.bibliography.opt.layout_suffix; - break; - } - } - topblobs[0].strings.prefix = this.bibliography.opt.layout_prefix + topblobs[0].strings.prefix; - } - CSL.Output.Queue.purgeEmptyBlobs(this.output.queue); - CSL.Output.Queue.adjustPunctuation(this, this.output.queue); - res = this.output.string(this, this.output.queue)[0]; - if (!res) { - res = "\n[CSL STYLE ERROR: reference with no printed form.]\n"; - } - ret.push(res); - } - var done = false; - if (bibsection && bibsection.page_start && bibsection.page_length) { - var last_expected_id = input.slice(-1)[0]; - var last_seen_id = processed_item_ids.slice(-1)[0]; - if (!last_expected_id || !last_seen_id || last_expected_id == last_seen_id) { - done = true; - } - } - this.tmp.disambig_override = false; - return [processed_item_ids, ret, done]; + this.keys = []; + this.opt.topdecor = []; }; CSL.Engine.prototype.previewCitationCluster = function (citation, citationsPre, citationsPost, newMode) { var oldMode = this.opt.mode; @@ -4541,301 +4131,670 @@ CSL.getCitationCluster = function (inputList, citationID) { delimiter: this.citation.opt.layout_delimiter } }; - var suffix = this.citation.opt.layout_suffix; - var last_locale = this.tmp.cite_locales[this.tmp.cite_locales.length - 1]; - if (last_locale && this.tmp.cite_affixes[last_locale] && this.tmp.cite_affixes[last_locale].suffix) { - suffix = this.tmp.cite_affixes[last_locale].suffix; + var suffix = this.citation.opt.layout_suffix; + var last_locale = this.tmp.cite_locales[this.tmp.cite_locales.length - 1]; + if (last_locale && this.tmp.cite_affixes[last_locale] && this.tmp.cite_affixes[last_locale].suffix) { + suffix = this.tmp.cite_affixes[last_locale].suffix; + } + if (CSL.TERMINAL_PUNCTUATION.slice(0, -1).indexOf(suffix.slice(0, 1)) > -1) { + suffix = suffix.slice(0, 1); + } + var delimiter = this.citation.opt.layout_delimiter; + if (!delimiter) { + delimiter = ""; + } + if (CSL.TERMINAL_PUNCTUATION.slice(0, -1).indexOf(delimiter.slice(0, 1)) > -1) { + delimiter = delimiter.slice(0, 1); + } + var mystk = [ + { + suffix: "", + delimiter: delimiter, + blob: fakeblob, + lastNode: true + } + ]; + var use_layout_suffix = suffix; + for (pos = 0, len = myblobs.length; pos < len; pos += 1) { + CSL.Output.Queue.purgeEmptyBlobs(this.output.queue, true); + } + for (pos = 0, len = myblobs.length; pos < len; pos += 1) { + this.output.queue = [myblobs[pos]]; + this.tmp.suppress_decorations = myparams[pos].suppress_decorations; + this.tmp.splice_delimiter = myparams[pos].splice_delimiter; + if (myblobs[pos].parallel_delimiter) { + this.tmp.splice_delimiter = myblobs[pos].parallel_delimiter; + } + this.tmp.have_collapsed = myparams[pos].have_collapsed; + if (pos === (myblobs.length - 1)) { + mystk[0].suffix = use_layout_suffix; + } + if (this.opt.development_extensions.clean_up_csl_flaws) { + CSL.Output.Queue.adjustPunctuation(this, this.output.queue, mystk); + } + composite = this.output.string(this, this.output.queue); + this.tmp.suppress_decorations = false; + if ("string" === typeof composite) { + this.tmp.suppress_decorations = false; + return composite; + } + if ("object" === typeof composite && composite.length === 0 && !item["suppress-author"]) { + if (this.tmp.has_purged_parallel) { + composite.push(""); + } else { + composite.push("[CSL STYLE ERROR: reference with no printed form.]"); + } + } + if (objects.length && "string" === typeof composite[0]) { + composite.reverse(); + var tmpstr = composite.pop(); + if (tmpstr && tmpstr.slice(0, 1) === ",") { + objects.push(tmpstr); + } else if ("string" == typeof objects.slice(-1)[0] && objects.slice(-1)[0].slice(-1) === ",") { + objects.push(" " + tmpstr); + } else if (tmpstr) { + objects.push(txt_esc(this.tmp.splice_delimiter) + tmpstr); + } + } else { + composite.reverse(); + compie = composite.pop(); + if ("undefined" !== typeof compie) { + if (objects.length && "string" === typeof objects[objects.length - 1]) { + objects[objects.length - 1] += compie.successor_prefix; + } + objects.push(compie); + } + } + llen = composite.length; + for (ppos = 0; ppos < llen; ppos += 1) { + obj = composite[ppos]; + if ("string" === typeof obj) { + objects.push(txt_esc(this.tmp.splice_delimiter) + obj); + continue; + } + compie = composite.pop(); + if ("undefined" !== typeof compie) { + objects.push(compie); + } + } + if (objects.length === 0 && !inputList[pos][1]["suppress-author"]) { + empties += 1; + } + } + result += this.output.renderBlobs(objects); + if (result) { + if (CSL.TERMINAL_PUNCTUATION.indexOf(this.tmp.last_chr) > -1 + && this.tmp.last_chr === use_layout_suffix.slice(0, 1)) { + use_layout_suffix = use_layout_suffix.slice(1); + } + this.output.nestedBraces = false; + if (!(this.opt.development_extensions.apply_citation_wrapper + && this.sys.wrapCitationEntry + && !this.tmp.just_looking + && this.tmp.area === "citation")) { + result = txt_esc(this.citation.opt.layout_prefix) + result + txt_esc(use_layout_suffix); + } + if (!this.tmp.suppress_decorations) { + len = this.citation.opt.layout_decorations.length; + for (pos = 0; pos < len; pos += 1) { + params = this.citation.opt.layout_decorations[pos]; + if (params[1] === "normal") { + continue; + } + result = this.fun.decorate[params[0]][params[1]](this, result); + } + } + } + this.tmp.suppress_decorations = false; + return result; +}; +CSL.getCite = function (Item, item, prevItemID) { + var next, error_object; + this.tmp.cite_renders_content = false; + this.parallel.StartCite(Item, item, prevItemID); + CSL.citeStart.call(this, Item, item); + next = 0; + this.nameOutput = new CSL.NameOutput(this, Item, item); + while (next < this[this.tmp.area].tokens.length) { + next = CSL.tokenExec.call(this, this[this.tmp.area].tokens[next], Item, item); + } + CSL.citeEnd.call(this, Item, item); + this.parallel.CloseCite(this); + if (!this.tmp.cite_renders_content && !this.tmp.just_looking) { + if (this.tmp.area === "bibliography") { + error_object = { + index: this.tmp.bibliography_pos, + itemID: "" + Item.id, + error_code: CSL.ERROR_NO_RENDERED_FORM + }; + this.tmp.bibliography_errors.push(error_object); + } + } + return "" + Item.id; +}; +CSL.citeStart = function (Item, item) { + this.tmp.disambiguate_count = 0; + this.tmp.disambiguate_maxMax = 0; + this.tmp.same_author_as_previous_cite = false; + if (!this.tmp.suppress_decorations) { + this.tmp.subsequent_author_substitute_ok = true; + } else { + this.tmp.subsequent_author_substitute_ok = false; + } + this.tmp.lastchr = ""; + if (this.tmp.area === "citation" && this.citation.opt.collapse && this.citation.opt.collapse.length) { + this.tmp.have_collapsed = true; + } else { + this.tmp.have_collapsed = false; + } + this.tmp.render_seen = false; + if (this.tmp.disambig_request && ! this.tmp.disambig_override) { + this.tmp.disambig_settings = this.tmp.disambig_request; + } else if (this.registry.registry[Item.id] && ! this.tmp.disambig_override) { + this.tmp.disambig_request = this.registry.registry[Item.id].disambig; + this.tmp.disambig_settings = this.registry.registry[Item.id].disambig; + } else { + this.tmp.disambig_settings = new CSL.AmbigConfig(); + } + if (this.tmp.area === 'bibliography' && this.opt["disambiguate-add-names"] && this.registry.registry[Item.id] && this.tmp.disambig_override) { + this.tmp.disambig_request = this.tmp.disambig_settings; + this.tmp.disambig_request.names = this.registry.registry[Item.id].disambig.names.slice(); + this.tmp.disambig_settings.names = this.registry.registry[Item.id].disambig.names.slice(); + } + this.tmp.names_used = []; + this.tmp.nameset_counter = 0; + this.tmp.years_used = []; + this.tmp.names_max.clear(); + this.tmp.splice_delimiter = this[this.tmp.area].opt.layout_delimiter; + this.bibliography_sort.keys = []; + this.citation_sort.keys = []; + this.tmp.has_done_year_suffix = false; + this.tmp.last_cite_locale = false; + if (!this.tmp.just_looking && item && !item.position && this.registry.registry[Item.id]) { + this.tmp.disambig_restore = CSL.cloneAmbigConfig(this.registry.registry[Item.id].disambig); + } + this.tmp.shadow_numbers = {}; + this.setNumberLabels(Item); + this.tmp.first_name_string = false; + if (this.opt.development_extensions.flip_parentheses_to_braces && item && item.prefix) { + var openBrace = CSL.checkNestedBraceOpen.exec(item.prefix); + var closeBrace = CSL.checkNestedBraceClose.exec(item.prefix); + if (openBrace) { + if (!closeBrace) { + this.output.nestedBraces = CSL.NestedBraces; + } else if (closeBrace[0].length < openBrace[0].length) { + this.output.nestedBraces = CSL.NestedBraces; + } else { + this.output.nestedBraces = false; + } + } else if (closeBrace) { + this.output.nestedBraces = false; + } + } +}; +CSL.citeEnd = function (Item, item) { + if (this.tmp.disambig_restore) { + this.registry.registry[Item.id].disambig.names = this.tmp.disambig_restore.names; + this.registry.registry[Item.id].disambig.givens = this.tmp.disambig_restore.givens; + } + this.tmp.disambig_restore = false; + this.tmp.last_suffix_used = this.tmp.suffix.value(); + this.tmp.last_years_used = this.tmp.years_used.slice(); + this.tmp.last_names_used = this.tmp.names_used.slice(); + this.tmp.cut_var = false; + this.tmp.disambig_request = false; + this.tmp.cite_locales.push(this.tmp.last_cite_locale); + if (this.tmp.issued_date && this.tmp.renders_collection_number) { + var buf = []; + for (var i = this.tmp.issued_date.list.length - 1; i > this.tmp.issued_date.pos; i += -1) { + buf.push(this.tmp.issued_date.list.pop()); + } + this.tmp.issued_date.list.pop(); + for (i = buf.length - 1; i > -1; i += -1) { + this.tmp.issued_date.list.push(buf.pop()); + } + if (this.parallel.use_parallels) { + this.parallel.cite["issued"] = false; + } + } + this.tmp.issued_date = false; + this.tmp.renders_collection_number = false; + if (this.opt.development_extensions.flip_parentheses_to_braces && item && item.suffix) { + var openBrace = CSL.checkNestedBraceOpen.exec(item.suffix); + var closeBrace = CSL.checkNestedBraceClose.exec(item.suffix); + if (closeBrace) { + if (!openBrace) { + this.output.nestedBraces = false; + } else if (openBrace[0].length < closeBrace[0].length) { + this.output.nestedBraces = false; + } else { + this.output.nestedBraces = CSL.NestedBraces; + } + } else if (openBrace) { + this.output.nestedBraces = CSL.NestedBraces; + } + } +}; +CSL.Engine.prototype.makeBibliography = function (bibsection) { + var debug, ret, params, maxoffset, item, len, pos, tok, tokk, tokkk, entry_ids, entry_strings, bibliography_errors; + debug = false; + if (!this.bibliography.tokens.length) { + return false; + } + if ("string" === typeof bibsection) { + this.opt.citation_number_slug = bibsection; + bibsection = false; + } + ret = CSL.getBibliographyEntries.call(this, bibsection); + entry_ids = ret[0]; + entry_strings = ret[1]; + var done = ret[2]; + params = { + "maxoffset": 0, + "entryspacing": this.bibliography.opt["entry-spacing"], + "linespacing": this.bibliography.opt["line-spacing"], + "second-field-align": false, + "entry_ids": entry_ids, + "bibliography_errors": this.tmp.bibliography_errors.slice(), + "done": done + }; + if (this.bibliography.opt["second-field-align"]) { + params["second-field-align"] = this.bibliography.opt["second-field-align"]; } - if (CSL.TERMINAL_PUNCTUATION.slice(0, -1).indexOf(suffix.slice(0, 1)) > -1) { - suffix = suffix.slice(0, 1); + maxoffset = 0; + len = this.registry.reflist.length; + for (pos = 0; pos < len; pos += 1) { + item = this.registry.reflist[pos]; + if (item.offset > params.maxoffset) { + params.maxoffset = item.offset; + } } - var delimiter = this.citation.opt.layout_delimiter; - if (!delimiter) { - delimiter = ""; + if (this.bibliography.opt.hangingindent) { + params.hangingindent = this.bibliography.opt.hangingindent; } - if (CSL.TERMINAL_PUNCTUATION.slice(0, -1).indexOf(delimiter.slice(0, 1)) > -1) { - delimiter = delimiter.slice(0, 1); + params.bibstart = this.fun.decorate.bibstart; + params.bibend = this.fun.decorate.bibend; + this.opt.citation_number_slug = false; + return [params, entry_strings]; +}; +CSL.getBibliographyEntries = function (bibsection) { + var ret, input, include, anymatch, allmatch, bib_entry, res, len, pos, item, llen, ppos, spec, lllen, pppos, bib_layout, topblobs, all_item_ids, entry_item_ids, debug, collapse_parallel, i, ilen, siblings, skips, sortedItems, eyetem, chr, entry_item_data, j, jlen, newIDs, originalIDs; + ret = []; + entry_item_data = []; + this.tmp.area = "bibliography"; + this.tmp.last_rendered_name = false; + this.tmp.bibliography_errors = []; + this.tmp.bibliography_pos = 0; + if (bibsection && bibsection.page_start && bibsection.page_length) { + input = this.registry.getSortedIds(); + } else { + input = this.retrieveItems(this.registry.getSortedIds()); } - var mystk = [ - { - suffix: "", - delimiter: delimiter, - blob: fakeblob, - lastNode: true + this.tmp.disambig_override = true; + function eval_string(a, b) { + if (a === b) { + return true; } - ]; - var use_layout_suffix = suffix; - for (pos = 0, len = myblobs.length; pos < len; pos += 1) { - CSL.Output.Queue.purgeEmptyBlobs(this.output.queue, true); + return false; } - for (pos = 0, len = myblobs.length; pos < len; pos += 1) { - this.output.queue = [myblobs[pos]]; - this.tmp.suppress_decorations = myparams[pos].suppress_decorations; - this.tmp.splice_delimiter = myparams[pos].splice_delimiter; - if (myblobs[pos].parallel_delimiter) { - this.tmp.splice_delimiter = myblobs[pos].parallel_delimiter; - } - this.tmp.have_collapsed = myparams[pos].have_collapsed; - if (pos === (myblobs.length - 1)) { - mystk[0].suffix = use_layout_suffix; + function eval_list(a, lst) { + lllen = lst.length; + for (pppos = 0; pppos < lllen; pppos += 1) { + if (eval_string(a, lst[pppos])) { + return true; + } } - if (this.opt.development_extensions.clean_up_csl_flaws) { - CSL.Output.Queue.adjustPunctuation(this, this.output.queue, mystk); + return false; + } + function eval_spec(a, b) { + if ((a === "none" || !a) && !b) { + return true; } - composite = this.output.string(this, this.output.queue); - this.tmp.suppress_decorations = false; - if ("string" === typeof composite) { - this.tmp.suppress_decorations = false; - return composite; + if ("string" === typeof b) { + return eval_string(a, b); + } else if (!b) { + return false; + } else { + return eval_list(a, b); } - if ("object" === typeof composite && composite.length === 0 && !item["suppress-author"]) { - if (this.tmp.has_purged_parallel) { - composite.push(""); - } else { - composite.push("[CSL STYLE ERROR: reference with no printed form.]"); + } + skips = {}; + var page_item_count; + if (bibsection && bibsection.page_start && bibsection.page_length) { + page_item_count = 0; + if (bibsection.page_start !== true) { + for (i = 0, ilen = input.length; i < ilen; i += 1) { + skips[input[i]] = true; + if (bibsection.page_start == input[i]) { + break; + } } } - if (objects.length && "string" === typeof composite[0]) { - composite.reverse(); - var tmpstr = composite.pop(); - if (tmpstr && tmpstr.slice(0, 1) === ",") { - objects.push(tmpstr); - } else if ("string" == typeof objects.slice(-1)[0] && objects.slice(-1)[0].slice(-1) === ",") { - objects.push(" " + tmpstr); - } else if (tmpstr) { - objects.push(txt_esc(this.tmp.splice_delimiter) + tmpstr); + } + var processed_item_ids = []; + for (i = 0, ilen = input.length; i < ilen; i += 1) { + if (bibsection && bibsection.page_start && bibsection.page_length) { + if (skips[input[i]]) { + continue; + } + item = this.retrieveItem(input[i]); + if (page_item_count === bibsection.page_length) { + break; } } else { - composite.reverse(); - compie = composite.pop(); - if ("undefined" !== typeof compie) { - if (objects.length && "string" === typeof objects[objects.length - 1]) { - objects[objects.length - 1] += compie.successor_prefix; - } - objects.push(compie); + item = input[i]; + if (skips[item.id]) { + continue; } } - llen = composite.length; - for (ppos = 0; ppos < llen; ppos += 1) { - obj = composite[ppos]; - if ("string" === typeof obj) { - objects.push(txt_esc(this.tmp.splice_delimiter) + obj); + if (bibsection) { + include = true; + if (bibsection.include) { + include = false; + for (j = 0, jlen = bibsection.include.length; j < jlen; j += 1) { + spec = bibsection.include[j]; + if (eval_spec(spec.value, item[spec.field])) { + include = true; + break; + } + } + } else if (bibsection.exclude) { + anymatch = false; + for (j = 0, jlen = bibsection.exclude.length; j < jlen; j += 1) { + spec = bibsection.exclude[j]; + if (eval_spec(spec.value, item[spec.field])) { + anymatch = true; + break; + } + } + if (anymatch) { + include = false; + } + } else if (bibsection.select) { + include = false; + allmatch = true; + for (j = 0, jlen = bibsection.select.length; j < jlen; j += 1) { + spec = bibsection.select[j]; + if (!eval_spec(spec.value, item[spec.field])) { + allmatch = false; + } + } + if (allmatch) { + include = true; + } + } + if (bibsection.quash) { + allmatch = true; + for (j = 0, jlen = bibsection.quash.length; j < jlen; j += 1) { + spec = bibsection.quash[j]; + if (!eval_spec(spec.value, item[spec.field])) { + allmatch = false; + } + } + if (allmatch) { + include = false; + } + } + if (!include) { continue; } - compie = composite.pop(); - if ("undefined" !== typeof compie) { - objects.push(compie); + } + bib_entry = new CSL.Token("group", CSL.START); + bib_entry.decorations = [["@bibliography", "entry"]].concat(this.bibliography.opt.layout_decorations); + this.output.startTag("bib_entry", bib_entry); + if (item.system_id && this.sys.embedBibliographyEntry) { + this.output.current.value().item_id = item.system_id; + } else { + this.output.current.value().system_id = item.id; + } + sortedItems = [[{id: "" + item.id}, item]]; + entry_item_ids = []; + if (this.registry.registry[item.id].master + && !(bibsection && bibsection.page_start && bibsection.page_length)) { + collapse_parallel = true; + this.parallel.StartCitation(sortedItems); + this.output.queue[0].strings.delimiter = ", "; + this.tmp.term_predecessor = false; + entry_item_ids.push("" + CSL.getCite.call(this, item)); + skips[item.id] = true; + siblings = this.registry.registry[item.id].siblings; + for (j = 0, jlen = siblings.length; j < jlen; j += 1) { + var k = this.registry.registry[item.id].siblings[j]; + eyetem = this.retrieveItem(k); + entry_item_ids.push("" + CSL.getCite.call(this, eyetem)); + skips[eyetem.id] = true; + } + this.parallel.ComposeSet(); + this.parallel.PruneOutputQueue(); + } else if (!this.registry.registry[item.id].siblings) { + this.parallel.StartCitation(sortedItems); + this.tmp.term_predecessor = false; + entry_item_ids.push("" + CSL.getCite.call(this, item)); + if (bibsection && bibsection.page_start && bibsection.page_length) { + page_item_count += 1; + } + } + entry_item_data.push(""); + this.tmp.bibliography_pos += 1; + processed_item_ids.push(entry_item_ids); + this.output.endTag("bib_entry"); + if (this.output.queue[0].blobs.length && this.output.queue[0].blobs[0].blobs.length) { + if (collapse_parallel || !this.output.queue[0].blobs[0].blobs[0].strings) { + topblobs = this.output.queue[0].blobs; + collapse_parallel = false; + } else { + topblobs = this.output.queue[0].blobs[0].blobs; + } + for (j = topblobs.length - 1; j > -1; j += -1) { + if (topblobs[j].blobs && topblobs[j].blobs.length !== 0) { + chr = this.bibliography.opt.layout_suffix.slice(0, 1); + if (chr && topblobs[j].strings.suffix.slice(-1) === chr) { + topblobs[j].strings.suffix = topblobs[j].strings.suffix.slice(0, -1); + } + topblobs[j].strings.suffix += this.bibliography.opt.layout_suffix; + break; + } } + topblobs[0].strings.prefix = this.bibliography.opt.layout_prefix + topblobs[0].strings.prefix; } - if (objects.length === 0 && !inputList[pos][1]["suppress-author"]) { - empties += 1; + CSL.Output.Queue.purgeEmptyBlobs(this.output.queue); + CSL.Output.Queue.adjustPunctuation(this, this.output.queue); + res = this.output.string(this, this.output.queue)[0]; + if (!res) { + res = "\n[CSL STYLE ERROR: reference with no printed form.]\n"; } + ret.push(res); } - result += this.output.renderBlobs(objects); - if (result) { - if (CSL.TERMINAL_PUNCTUATION.indexOf(this.tmp.last_chr) > -1 - && this.tmp.last_chr === use_layout_suffix.slice(0, 1)) { - use_layout_suffix = use_layout_suffix.slice(1); - } - this.output.nestedBraces = false; - if (!(this.opt.development_extensions.apply_citation_wrapper - && this.sys.wrapCitationEntry - && !this.tmp.just_looking - && this.tmp.area === "citation")) { - result = txt_esc(this.citation.opt.layout_prefix) + result + txt_esc(use_layout_suffix); - } - if (!this.tmp.suppress_decorations) { - len = this.citation.opt.layout_decorations.length; - for (pos = 0; pos < len; pos += 1) { - params = this.citation.opt.layout_decorations[pos]; - if (params[1] === "normal") { - continue; - } - result = this.fun.decorate[params[0]][params[1]](this, result); - } + var done = false; + if (bibsection && bibsection.page_start && bibsection.page_length) { + var last_expected_id = input.slice(-1)[0]; + var last_seen_id = processed_item_ids.slice(-1)[0]; + if (!last_expected_id || !last_seen_id || last_expected_id == last_seen_id) { + done = true; } } - this.tmp.suppress_decorations = false; - return result; + this.tmp.disambig_override = false; + return [processed_item_ids, ret, done]; }; -CSL.getCite = function (Item, item, prevItemID) { - var next, error_object; - this.tmp.cite_renders_content = false; - this.parallel.StartCite(Item, item, prevItemID); - CSL.citeStart.call(this, Item, item); - next = 0; - this.nameOutput = new CSL.NameOutput(this, Item, item); - while (next < this[this.tmp.area].tokens.length) { - next = CSL.tokenExec.call(this, this[this.tmp.area].tokens[next], Item, item); - } - CSL.citeEnd.call(this, Item, item); - this.parallel.CloseCite(this); - if (!this.tmp.cite_renders_content && !this.tmp.just_looking) { - if (this.tmp.area === "bibliography") { - error_object = { - index: this.tmp.bibliography_pos, - itemID: "" + Item.id, - error_code: CSL.ERROR_NO_RENDERED_FORM - }; - this.tmp.bibliography_errors.push(error_object); +CSL.Engine.prototype.setCitationId = function (citation, force) { + var ret, id, direction; + ret = false; + if (!citation.citationID || force) { + id = Math.floor(Math.random() * 100000000000000); + while (true) { + direction = 0; + if (!this.registry.citationreg.citationById[id]) { + citation.citationID = id.toString(32); + break; + } else if (!direction && id < 50000000000000) { + direction = 1; + } else { + direction = -1; + } + if (direction === 1) { + id += 1; + } else { + id += -1; + } } + ret = "" + id; } - return "" + Item.id; + this.registry.citationreg.citationById[citation.citationID] = citation; + return ret; }; -CSL.citeStart = function (Item, item) { - this.tmp.disambiguate_count = 0; - this.tmp.disambiguate_maxMax = 0; - this.tmp.same_author_as_previous_cite = false; - if (!this.tmp.suppress_decorations) { - this.tmp.subsequent_author_substitute_ok = true; - } else { - this.tmp.subsequent_author_substitute_ok = false; +CSL.Engine.prototype.rebuildProcessorState = function (citations, mode, uncitedItemIDs) { + if (!citations) { + citations = []; } - this.tmp.lastchr = ""; - if (this.tmp.area === "citation" && this.citation.opt.collapse && this.citation.opt.collapse.length) { - this.tmp.have_collapsed = true; - } else { - this.tmp.have_collapsed = false; + if (!mode) { + mode = 'html'; } - this.tmp.render_seen = false; - if (this.tmp.disambig_request && ! this.tmp.disambig_override) { - this.tmp.disambig_settings = this.tmp.disambig_request; - } else if (this.registry.registry[Item.id] && ! this.tmp.disambig_override) { - this.tmp.disambig_request = this.registry.registry[Item.id].disambig; - this.tmp.disambig_settings = this.registry.registry[Item.id].disambig; - } else { - this.tmp.disambig_settings = new CSL.AmbigConfig(); + var itemIDs = []; + for (var i=0,ilen=citations.length;i<ilen;i+=1) { + for (var j=0,jlen=citations[i].citationItems.length;j<jlen;j+=1) { + var itemID = "" + citations[i].citationItems[j].id; + itemIDs.push(itemID); + } } - if (this.tmp.area === 'bibliography' && this.opt["disambiguate-add-names"] && this.registry.registry[Item.id] && this.tmp.disambig_override) { - this.tmp.disambig_request = this.tmp.disambig_settings; - this.tmp.disambig_request.names = this.registry.registry[Item.id].disambig.names.slice(); - this.tmp.disambig_settings.names = this.registry.registry[Item.id].disambig.names.slice(); + this.updateItems(itemIDs); + var pre = []; + var post = []; + var ret = []; + var oldMode = this.opt.mode; + this.setOutputFormat(mode); + for (var i=0,ilen=citations.length;i<ilen;i+=1) { + var res = this.processCitationCluster(citations[i],pre,post,CSL.ASSUME_ALL_ITEMS_REGISTERED); + pre.push([citations[i].citationID,citations[i].properties.noteIndex]); + for (var j=0,jlen=res[1].length;j<jlen;j+=1) { + var index = res[1][j][0]; + ret[index] = [ + pre[index][0], + pre[index][1], + res[1][j][1] + ]; + } } - this.tmp.names_used = []; - this.tmp.nameset_counter = 0; - this.tmp.years_used = []; - this.tmp.names_max.clear(); - this.tmp.splice_delimiter = this[this.tmp.area].opt.layout_delimiter; - this.bibliography_sort.keys = []; - this.citation_sort.keys = []; - this.tmp.has_done_year_suffix = false; - this.tmp.last_cite_locale = false; - if (!this.tmp.just_looking && item && !item.position && this.registry.registry[Item.id]) { - this.tmp.disambig_restore = CSL.cloneAmbigConfig(this.registry.registry[Item.id].disambig); + this.updateUncitedItems(uncitedItemIDs); + this.setOutputFormat(oldMode); + return ret; +} +CSL.Engine.prototype.restoreProcessorState = function (citations) { + var i, ilen, j, jlen, item, Item, newitem, citationList, itemList, sortedItems; + citationList = []; + itemList = []; + if (!citations) { + citations = []; } - this.tmp.shadow_numbers = {}; - this.setNumberLabels(Item); - this.tmp.first_name_string = false; - if (this.opt.development_extensions.flip_parentheses_to_braces && item && item.prefix) { - var openBrace = CSL.checkNestedBraceOpen.exec(item.prefix); - var closeBrace = CSL.checkNestedBraceClose.exec(item.prefix); - if (openBrace) { - if (!closeBrace) { - this.output.nestedBraces = CSL.NestedBraces; - } else if (closeBrace[0].length < openBrace[0].length) { - this.output.nestedBraces = CSL.NestedBraces; + var indexNumbers = []; + var citationIds = {}; + for (i = 0, ilen = citations.length; i < ilen; i += 1) { + if (citationIds[citations[i].citationID]) { + this.setCitationId(citations[i], true); + } + citationIds[citations[i].citationID] = true; + indexNumbers.push(citations[i].properties.index); + } + var oldCitations = citations.slice(); + oldCitations.sort( + function (a,b) { + if (a.properties.index < b.properties.index) { + return -1; + } else if (a.properties.index > b.properties.index) { + return 1; } else { - this.output.nestedBraces = false; + return 0; } - } else if (closeBrace) { - this.output.nestedBraces = false; } + ); + for (i = 0, ilen = oldCitations.length; i < ilen; i += 1) { + oldCitations[i].properties.index = i; } -}; -CSL.citeEnd = function (Item, item) { - if (this.tmp.disambig_restore) { - this.registry.registry[Item.id].disambig.names = this.tmp.disambig_restore.names; - this.registry.registry[Item.id].disambig.givens = this.tmp.disambig_restore.givens; - } - this.tmp.disambig_restore = false; - this.tmp.last_suffix_used = this.tmp.suffix.value(); - this.tmp.last_years_used = this.tmp.years_used.slice(); - this.tmp.last_names_used = this.tmp.names_used.slice(); - this.tmp.cut_var = false; - this.tmp.disambig_request = false; - this.tmp.cite_locales.push(this.tmp.last_cite_locale); - if (this.tmp.issued_date && this.tmp.renders_collection_number) { - var buf = []; - for (var i = this.tmp.issued_date.list.length - 1; i > this.tmp.issued_date.pos; i += -1) { - buf.push(this.tmp.issued_date.list.pop()); - } - this.tmp.issued_date.list.pop(); - for (i = buf.length - 1; i > -1; i += -1) { - this.tmp.issued_date.list.push(buf.pop()); + for (i = 0, ilen = oldCitations.length; i < ilen; i += 1) { + sortedItems = []; + for (j = 0, jlen = oldCitations[i].citationItems.length; j < jlen; j += 1) { + item = oldCitations[i].citationItems[j]; + if ("undefined" === typeof item.sortkeys) { + item.sortkeys = []; + } + Item = this.retrieveItem("" + item.id); + newitem = [Item, item]; + sortedItems.push(newitem); + oldCitations[i].citationItems[j].item = Item; + itemList.push("" + item.id); } - if (this.parallel.use_parallels) { - this.parallel.cite["issued"] = false; + if (!oldCitations[i].properties.unsorted) { + sortedItems.sort(this.citation.srt.compareCompositeKeys); } + oldCitations[i].sortedItems = sortedItems; + this.registry.citationreg.citationById[oldCitations[i].citationID] = oldCitations[i]; } - this.tmp.issued_date = false; - this.tmp.renders_collection_number = false; - if (this.opt.development_extensions.flip_parentheses_to_braces && item && item.suffix) { - var openBrace = CSL.checkNestedBraceOpen.exec(item.suffix); - var closeBrace = CSL.checkNestedBraceClose.exec(item.suffix); - if (closeBrace) { - if (!openBrace) { - this.output.nestedBraces = false; - } else if (openBrace[0].length < closeBrace[0].length) { - this.output.nestedBraces = false; - } else { - this.output.nestedBraces = CSL.NestedBraces; - } - } else if (openBrace) { - this.output.nestedBraces = CSL.NestedBraces; - } + this.updateItems(itemList); + for (i = 0, ilen = citations.length; i < ilen; i += 1) { + citationList.push(["" + citations[i].citationID, citations[i].properties.noteIndex]); + } + var ret = []; + if (citations && citations.length) { + ret = this.processCitationCluster(citations[0], [], citationList.slice(1)); + } else { + this.registry = new CSL.Registry(this); + this.tmp = new CSL.Engine.Tmp(); + this.disambiguate = new CSL.Disambiguation(this); } + return ret; }; -CSL.Node = {}; -CSL.Node.bibliography = { - build: function (state, target) { - if (this.tokentype === CSL.START) { - state.build.area = "bibliography"; - state.build.root = "bibliography"; - state.fixOpt(this, "names-delimiter", "delimiter"); - state.fixOpt(this, "name-delimiter", "delimiter"); - state.fixOpt(this, "name-form", "form"); - state.fixOpt(this, "and", "and"); - state.fixOpt(this, "delimiter-precedes-last", "delimiter-precedes-last"); - state.fixOpt(this, "delimiter-precedes-et-al", "delimiter-precedes-et-al"); - state.fixOpt(this, "initialize-with", "initialize-with"); - state.fixOpt(this, "initialize", "initialize"); - state.fixOpt(this, "name-as-sort-order", "name-as-sort-order"); - state.fixOpt(this, "sort-separator", "sort-separator"); - state.fixOpt(this, "and", "and"); - state.fixOpt(this, "et-al-min", "et-al-min"); - state.fixOpt(this, "et-al-use-first", "et-al-use-first"); - state.fixOpt(this, "et-al-use-last", "et-al-use-last"); - state.fixOpt(this, "et-al-subsequent-min", "et-al-subsequent-min"); - state.fixOpt(this, "et-al-subsequent-use-first", "et-al-subsequent-use-first"); +CSL.Engine.prototype.updateItems = function (idList, nosort, rerun_ambigs) { + var debug = false; + var oldArea = this.tmp.area; + this.registry.init(idList); + if (rerun_ambigs) { + for (var ambig in this.registry.ambigcites) { + this.registry.ambigsTouched[ambig] = true; } - target.push(this); } + this.registry.dodeletes(this.registry.myhash); + this.registry.doinserts(this.registry.mylist); + this.registry.dorefreshes(); + this.registry.rebuildlist(); + this.registry.setsortkeys(); + this.registry.setdisambigs(); + if (!nosort) { + this.registry.sorttokens(); + } + this.registry.renumber(); + this.tmp.area = oldArea; + return this.registry.getSortedIds(); }; -CSL.Node.choose = { - build: function (state, target) { - var func; - if (this.tokentype === CSL.START) { - func = function (state, Item) { - state.tmp.jump.push(undefined, CSL.LITERAL); - }; - } - if (this.tokentype === CSL.END) { - func = function (state, Item) { - state.tmp.jump.pop(); - }; - } - this.execs.push(func); - target.push(this); - }, - configure: function (state, pos) { - if (this.tokentype === CSL.END) { - state.configure.fail.push((pos)); - state.configure.succeed.push((pos)); - } else { - state.configure.fail.pop(); - state.configure.succeed.pop(); +CSL.Engine.prototype.updateUncitedItems = function (idList, nosort) { + var debug = false; + if (!idList) { + idList = []; + } + if ("object" == typeof idList) { + if ("undefined" == typeof idList.length) { + var idHash = idList; + idList = []; + for (var key in idHash) { + idList.push(key); + } + } else if ("number" == typeof idList.length) { + var idHash = {}; + for (var i=0,ilen=idList.length;i<ilen;i+=1) { + idHash[idList[i]] = true; + } } } + this.registry.init(idList, true); + this.registry.dopurge(idHash); + this.registry.doinserts(this.registry.mylist); + this.registry.dorefreshes(); + this.registry.rebuildlist(); + this.registry.setsortkeys(); + this.registry.setdisambigs(); + if (!nosort) { + this.registry.sorttokens(); + } + this.registry.renumber(); + return this.registry.getSortedIds(); }; CSL.localeResolve = function (langstr) { var ret, langlst; @@ -5078,6 +5037,58 @@ CSL.Engine.prototype.localeSet = function (myxml, lang_in, lang_out) { } } }; +CSL.Node = {}; +CSL.Node.bibliography = { + build: function (state, target) { + if (this.tokentype === CSL.START) { + state.build.area = "bibliography"; + state.build.root = "bibliography"; + state.fixOpt(this, "names-delimiter", "delimiter"); + state.fixOpt(this, "name-delimiter", "delimiter"); + state.fixOpt(this, "name-form", "form"); + state.fixOpt(this, "and", "and"); + state.fixOpt(this, "delimiter-precedes-last", "delimiter-precedes-last"); + state.fixOpt(this, "delimiter-precedes-et-al", "delimiter-precedes-et-al"); + state.fixOpt(this, "initialize-with", "initialize-with"); + state.fixOpt(this, "initialize", "initialize"); + state.fixOpt(this, "name-as-sort-order", "name-as-sort-order"); + state.fixOpt(this, "sort-separator", "sort-separator"); + state.fixOpt(this, "and", "and"); + state.fixOpt(this, "et-al-min", "et-al-min"); + state.fixOpt(this, "et-al-use-first", "et-al-use-first"); + state.fixOpt(this, "et-al-use-last", "et-al-use-last"); + state.fixOpt(this, "et-al-subsequent-min", "et-al-subsequent-min"); + state.fixOpt(this, "et-al-subsequent-use-first", "et-al-subsequent-use-first"); + } + target.push(this); + } +}; +CSL.Node.choose = { + build: function (state, target) { + var func; + if (this.tokentype === CSL.START) { + func = function (state, Item) { + state.tmp.jump.push(undefined, CSL.LITERAL); + }; + } + if (this.tokentype === CSL.END) { + func = function (state, Item) { + state.tmp.jump.pop(); + }; + } + this.execs.push(func); + target.push(this); + }, + configure: function (state, pos) { + if (this.tokentype === CSL.END) { + state.configure.fail.push((pos)); + state.configure.succeed.push((pos)); + } else { + state.configure.fail.pop(); + state.configure.succeed.pop(); + } + } +}; CSL.Node.citation = { build: function (state, target) { if (this.tokentype === CSL.START) { @@ -5116,6 +5127,10 @@ CSL.Node.citation = { } } }; +CSL.Node["#comment"] = { + build: function (state, target) { + } +}; CSL.Node.date = { build: function (state, target) { var func, date_obj, tok, len, pos, part, dpx, parts, mypos, start, end; @@ -5444,6 +5459,8 @@ CSL.Node["else-if"] = { if (this.locale) { state.opt.lang = this.locale; } + var func = state.fun.match[this.match](this, state, this.rawtests, CSL.CONDITION_LEVEL_BOTTOM); + this.tests.push(func); if (!this.evaluator) { this.evaluator = function (token, state, Item, item) { var record = function (result) { @@ -5501,10 +5518,6 @@ CSL.Node["else"] = { } } }; -CSL.Node["#comment"] = { - build: function (state, target) { - } -}; CSL.Node["et-al"] = { build: function (state, target) { if (state.build.area === "citation" || state.build.area === "bibliography") { @@ -5617,6 +5630,8 @@ CSL.Node["if"] = { if (this.locale) { state.opt.lang = this.locale; } + var func = state.fun.match[this.match](this, state, this.rawtests, CSL.CONDITION_LEVEL_BOTTOM); + this.tests.push(func); if (!this.evaluator) { this.evaluator = function (token, state, Item, item) { var record = function (result) { @@ -6705,131 +6720,59 @@ CSL.NameOutput.prototype._joinEllipsis = function (blobs, tokenname) { return this._join(blobs, this.name.strings.delimiter, this.name.ellipsis.single, this.name.ellipsis.multiple, tokenname); }; CSL.NameOutput.prototype._joinAnd = function (blobs, tokenname) { - return this._join(blobs, this[tokenname].strings.delimiter, this[tokenname].and.single, this[tokenname].and.multiple, tokenname); -}; -CSL.NameOutput.prototype._join = function (blobs, delimiter, single, multiple, tokenname) { - var i, ilen; - if (!blobs) { - return false; - } - for (i = blobs.length - 1; i > -1; i += -1) { - if (!blobs[i] || blobs[i].length === 0 || !blobs[i].blobs.length) { - blobs = blobs.slice(0, i).concat(blobs.slice(i + 1)); - } - } - if (!blobs.length) { - return false; - } else if (single && blobs.length === 2) { - blobs = [blobs[0], single, blobs[1]]; - } else { - var delimiter_offset; - if (multiple) { - delimiter_offset = 2; - } else { - delimiter_offset = 1; - } - for (i = 0, ilen = blobs.length - delimiter_offset; i < ilen; i += 1) { - blobs[i].strings.suffix += delimiter; - } - if (blobs.length > 1) { - var blob = blobs.pop(); - if (multiple) { - blobs.push(multiple); - } else { - blobs.push(single); - } - blobs.push(blob); - } - } - this.state.output.openLevel(this._getToken(tokenname)); - if (single && multiple) { - this.state.output.current.value().strings.delimiter = ""; - } - for (i = 0, ilen = blobs.length; i < ilen; i += 1) { - this.state.output.append(blobs[i], false, true); - } - this.state.output.closeLevel(); - return this.state.output.pop(); -}; -CSL.NameOutput.prototype._getToken = function (tokenname) { - var token = this[tokenname]; - if (tokenname === "institution") { - var newtoken = new CSL.Token(); - return newtoken; - } - return token; -}; -CSL.NameOutput.prototype.disambigNames = function () { - var pos = this.nameset_base; - for (var i = 0, ilen = this.variables.length; i < ilen; i += 1) { - var v = this.variables[i]; - if (this.freeters[v].length) { - this._runDisambigNames(this.freeters[v], pos); - pos += 1; - } - if (this.institutions[v].length) { - pos += 1; - } - for (var j = 0, jlen = this.persons[v].length; j < jlen; j += 1) { - if (this.persons[v][j].length) { - this._runDisambigNames(this.persons[v][j], pos); - this.state.tmp.disambig_settings.givens.push([]); - pos += 1; - } - } - } -}; -CSL.NameOutput.prototype._runDisambigNames = function (lst, pos) { - var chk, myform, myinitials, param, i, ilen, paramx; - for (i = 0, ilen = lst.length; i < ilen; i += 1) { - if (!lst[i].given && !lst[i].family) { - continue; - } - myinitials = this.name.strings["initialize-with"]; - this.state.registry.namereg.addname("" + this.Item.id, lst[i], i); - chk = this.state.tmp.disambig_settings.givens[pos]; - if ("undefined" === typeof chk) { - for (var j = 0, jlen = pos + 1; j < jlen; j += 1) { - if (!this.state.tmp.disambig_settings.givens[j]) { - this.state.tmp.disambig_settings.givens[j] = []; - } - } - } - chk = this.state.tmp.disambig_settings.givens[pos][i]; - if ("undefined" === typeof chk) { - myform = this.name.strings.form; - param = this.state.registry.namereg.evalname("" + this.Item.id, lst[i], i, 0, myform, myinitials); - this.state.tmp.disambig_settings.givens[pos].push(param); + return this._join(blobs, this[tokenname].strings.delimiter, this[tokenname].and.single, this[tokenname].and.multiple, tokenname); +}; +CSL.NameOutput.prototype._join = function (blobs, delimiter, single, multiple, tokenname) { + var i, ilen; + if (!blobs) { + return false; + } + for (i = blobs.length - 1; i > -1; i += -1) { + if (!blobs[i] || blobs[i].length === 0 || !blobs[i].blobs.length) { + blobs = blobs.slice(0, i).concat(blobs.slice(i + 1)); } - myform = this.name.strings.form; - paramx = this.state.registry.namereg.evalname("" + this.Item.id, lst[i], i, 0, myform, myinitials); - if (this.state.tmp.disambig_request) { - var val = this.state.tmp.disambig_settings.givens[pos][i]; - if (val === 1 && - this.state.citation.opt["givenname-disambiguation-rule"] === "by-cite" && - ("undefined" === typeof this.name.strings["initialize-with"] - || "undefined" === typeof lst[i].given)) { - val = 2; - } - param = val; - if (this.state.opt["disambiguate-add-givenname"] && lst[i].given) { - param = this.state.registry.namereg.evalname("" + this.Item.id, lst[i], i, param, this.name.strings.form, this.name.strings["initialize-with"]); - } + } + if (!blobs.length) { + return false; + } else if (single && blobs.length === 2) { + blobs = [blobs[0], single, blobs[1]]; + } else { + var delimiter_offset; + if (multiple) { + delimiter_offset = 2; } else { - param = paramx; + delimiter_offset = 1; } - if (!this.state.tmp.just_looking && this.item && this.item.position === CSL.POSITION_FIRST) { - param = paramx; + for (i = 0, ilen = blobs.length - delimiter_offset; i < ilen; i += 1) { + blobs[i].strings.suffix += delimiter; } - if (!this.state.tmp.sort_key_flag) { - this.state.tmp.disambig_settings.givens[pos][i] = param; - if ("string" === typeof myinitials - && ("undefined" === typeof this.name.strings["initialize"] - || true === this.name.strings["initialize"])) { - this.state.tmp.disambig_settings.use_initials = true; + if (blobs.length > 1) { + var blob = blobs.pop(); + if (multiple) { + blobs.push(multiple); + } else { + blobs.push(single); } + blobs.push(blob); } } + this.state.output.openLevel(this._getToken(tokenname)); + if (single && multiple) { + this.state.output.current.value().strings.delimiter = ""; + } + for (i = 0, ilen = blobs.length; i < ilen; i += 1) { + this.state.output.append(blobs[i], false, true); + } + this.state.output.closeLevel(); + return this.state.output.pop(); +}; +CSL.NameOutput.prototype._getToken = function (tokenname) { + var token = this[tokenname]; + if (tokenname === "institution") { + var newtoken = new CSL.Token(); + return newtoken; + } + return token; }; CSL.NameOutput.prototype.setCommonTerm = function () { var variables = this.variables; @@ -6959,6 +6902,78 @@ CSL.NameOutput.prototype._imposeNameConstraints = function (lst, count, key, pos this.state.tmp.disambig_settings.names[pos] = lst[key].length; this.state.disambiguate.padBase(this.state.tmp.disambig_settings); }; +CSL.NameOutput.prototype.disambigNames = function () { + var pos = this.nameset_base; + for (var i = 0, ilen = this.variables.length; i < ilen; i += 1) { + var v = this.variables[i]; + if (this.freeters[v].length) { + this._runDisambigNames(this.freeters[v], pos); + pos += 1; + } + if (this.institutions[v].length) { + pos += 1; + } + for (var j = 0, jlen = this.persons[v].length; j < jlen; j += 1) { + if (this.persons[v][j].length) { + this._runDisambigNames(this.persons[v][j], pos); + this.state.tmp.disambig_settings.givens.push([]); + pos += 1; + } + } + } +}; +CSL.NameOutput.prototype._runDisambigNames = function (lst, pos) { + var chk, myform, myinitials, param, i, ilen, paramx; + for (i = 0, ilen = lst.length; i < ilen; i += 1) { + if (!lst[i].given && !lst[i].family) { + continue; + } + myinitials = this.name.strings["initialize-with"]; + this.state.registry.namereg.addname("" + this.Item.id, lst[i], i); + chk = this.state.tmp.disambig_settings.givens[pos]; + if ("undefined" === typeof chk) { + for (var j = 0, jlen = pos + 1; j < jlen; j += 1) { + if (!this.state.tmp.disambig_settings.givens[j]) { + this.state.tmp.disambig_settings.givens[j] = []; + } + } + } + chk = this.state.tmp.disambig_settings.givens[pos][i]; + if ("undefined" === typeof chk) { + myform = this.name.strings.form; + param = this.state.registry.namereg.evalname("" + this.Item.id, lst[i], i, 0, myform, myinitials); + this.state.tmp.disambig_settings.givens[pos].push(param); + } + myform = this.name.strings.form; + paramx = this.state.registry.namereg.evalname("" + this.Item.id, lst[i], i, 0, myform, myinitials); + if (this.state.tmp.disambig_request) { + var val = this.state.tmp.disambig_settings.givens[pos][i]; + if (val === 1 && + this.state.citation.opt["givenname-disambiguation-rule"] === "by-cite" && + ("undefined" === typeof this.name.strings["initialize-with"] + || "undefined" === typeof lst[i].given)) { + val = 2; + } + param = val; + if (this.state.opt["disambiguate-add-givenname"] && lst[i].given) { + param = this.state.registry.namereg.evalname("" + this.Item.id, lst[i], i, param, this.name.strings.form, this.name.strings["initialize-with"]); + } + } else { + param = paramx; + } + if (!this.state.tmp.just_looking && this.item && this.item.position === CSL.POSITION_FIRST) { + param = paramx; + } + if (!this.state.tmp.sort_key_flag) { + this.state.tmp.disambig_settings.givens[pos][i] = param; + if ("string" === typeof myinitials + && ("undefined" === typeof this.name.strings["initialize"] + || true === this.name.strings["initialize"])) { + this.state.tmp.disambig_settings.use_initials = true; + } + } + } +}; CSL.NameOutput.prototype.getEtAlConfig = function () { var item = this.item; this["et-al"] = {}; @@ -7005,6 +7020,40 @@ CSL.NameOutput.prototype.getEtAlConfig = function () { this.state.tmp["et-al-min"] = this.etal_min; } }; +CSL.NameOutput.prototype.setEtAlParameters = function () { + var i, ilen, j, jlen; + for (i = 0, ilen = this.variables.length; i < ilen; i += 1) { + var v = this.variables[i]; + if (this.freeters[v].length) { + this._setEtAlParameter("freeters", v); + } + if (this.institutions[v].length) { + this._setEtAlParameter("institutions", v); + } + for (j = 0, jlen = this.persons[v].length; j < jlen; j += 1) { + this._setEtAlParameter("persons", v, j); + } + } +}; +CSL.NameOutput.prototype._setEtAlParameter = function (type, v, j) { + var lst, count; + if ("undefined" === typeof j) { + lst = this[type][v]; + count = this[type + "_count"][v]; + } else { + lst = this[type][v][j]; + count = this[type + "_count"][v][j]; + } + if (lst.length < count && !this.state.tmp.sort_key_flag) { + if (this.etal_use_last) { + this.etal_spec.push(2); + } else { + this.etal_spec.push(1); + } + } else { + this.etal_spec.push(0); + } +}; CSL.NameOutput.prototype.renderAllNames = function () { var pos = this.nameset_base; for (var i = 0, ilen = this.variables.length; i < ilen; i += 1) { @@ -7770,148 +7819,38 @@ CSL.NameOutput.prototype._trimInstitution = function (subunits, v, i) { append_last = this.institution.strings["use-last"]; } } - if (false === use_first) { - if (this.persons[v].length === 0) { - use_first = this.institution.strings["substitute-use-first"]; - } - if (!use_first) { - use_first = 0; - } - } - if (false === append_last) { - if (!use_first) { - append_last = subunits.length; - } else { - append_last = 0; - } - } - if (use_first > subunits.length - append_last) { - use_first = subunits.length - append_last; - } - if (stop_last) { - append_last = 0; - } - subunits = subunits.slice(0, use_first); - s = s.slice(use_first); - if (append_last) { - if (append_last > s.length) { - append_last = s.length; - } - if (append_last) { - subunits = subunits.concat(s.slice((s.length - append_last))); - } - } - return subunits; -}; -CSL.NameOutput.prototype.setEtAlParameters = function () { - var i, ilen, j, jlen; - for (i = 0, ilen = this.variables.length; i < ilen; i += 1) { - var v = this.variables[i]; - if (this.freeters[v].length) { - this._setEtAlParameter("freeters", v); - } - if (this.institutions[v].length) { - this._setEtAlParameter("institutions", v); - } - for (j = 0, jlen = this.persons[v].length; j < jlen; j += 1) { - this._setEtAlParameter("persons", v, j); - } - } -}; -CSL.NameOutput.prototype._setEtAlParameter = function (type, v, j) { - var lst, count; - if ("undefined" === typeof j) { - lst = this[type][v]; - count = this[type + "_count"][v]; - } else { - lst = this[type][v][j]; - count = this[type + "_count"][v][j]; - } - if (lst.length < count && !this.state.tmp.sort_key_flag) { - if (this.etal_use_last) { - this.etal_spec.push(2); - } else { - this.etal_spec.push(1); - } - } else { - this.etal_spec.push(0); - } -}; -CSL.evaluateLabel = function (node, state, Item, item) { - var myterm; - if ("locator" === node.strings.term) { - if (item && item.label) { - if (item.label === "sub verbo") { - myterm = "sub-verbo"; - } else { - myterm = item.label; - } - } - if (!myterm) { - myterm = "page"; - } - } else { - myterm = node.strings.term; - } - var plural = node.strings.plural; - if (item && "number" === typeof item.force_pluralism) { - plural = item.force_pluralism; - } else if ("number" !== typeof plural) { - if ("locator" === node.strings.term) { - if (item && item.locator) { - if (state.opt.development_extensions.locator_parsing_for_plurals) { - if (!state.tmp.shadow_numbers.locator) { - state.processNumber(false, item, "locator", Item.type); - } - plural = state.tmp.shadow_numbers.locator.plural; - } else { - plural = CSL.evaluateStringPluralism(item.locator); - } - } - } else if (["page", "page-first"].indexOf(node.variables[0]) > -1) { - state.processNumber(false, Item, myterm, Item.type); - plural = state.tmp.shadow_numbers[myterm].plural; - myterm = state.tmp.shadow_numbers[myterm].label; - } else { - if (!state.tmp.shadow_numbers[myterm]) { - state.processNumber(false, Item, myterm, Item.type); - } - plural = state.tmp.shadow_numbers[myterm].plural; + if (false === use_first) { + if (this.persons[v].length === 0) { + use_first = this.institution.strings["substitute-use-first"]; } - if (node.decorations && state.opt.development_extensions.csl_reverse_lookup_support) { - node.decorations.reverse(); - node.decorations.push(["@showid","true", node.cslid]); - node.decorations.reverse(); + if (!use_first) { + use_first = 0; } } - return CSL.castLabel(state, node, myterm, plural, CSL.TOLERANT); -}; -CSL.evaluateStringPluralism = function (str) { - if (str) { - var m = str.match(/(?:[0-9],\s*[0-9]|\s+and\s+|&|([0-9]+)\s*[\-\u2013]\s*([0-9]+))/); - if (m && (!m[1] || parseInt(m[1], 10) < parseInt(m[2], 10))) { - return 1; + if (false === append_last) { + if (!use_first) { + append_last = subunits.length; + } else { + append_last = 0; } } - return 0; -}; -CSL.castLabel = function (state, node, term, plural, mode) { - var label_form = node.strings.form; - if (state.tmp.group_context.value()[5]) { - label_form = state.tmp.group_context.value()[5]; + if (use_first > subunits.length - append_last) { + use_first = subunits.length - append_last; } - var ret = state.getTerm(term, label_form, plural, false, mode); - if (state.tmp.strip_periods) { - ret = ret.replace(/\./g, ""); - } else { - for (var i = 0, ilen = node.decorations.length; i < ilen; i += 1) { - if ("@strip-periods" === node.decorations[i][0] && "true" === node.decorations[i][1]) { - ret = ret.replace(/\./g, ""); - break; - } + if (stop_last) { + append_last = 0; + } + subunits = subunits.slice(0, use_first); + s = s.slice(use_first); + if (append_last) { + if (append_last > s.length) { + append_last = s.length; + } + if (append_last) { + subunits = subunits.concat(s.slice((s.length - append_last))); } } - return ret; + return subunits; }; CSL.PublisherOutput = function (state, group_tok) { this.state = state; @@ -7989,89 +7928,77 @@ CSL.PublisherOutput.prototype.clearVars = function () { this.state.tmp["publisher-token"] = false; this.state.tmp["publisher-place-token"] = false; }; -CSL.dateMacroAsSortKey = function (state, Item) { - CSL.dateAsSortKey.call(this, state, Item, true); -}; -CSL.dateAsSortKey = function (state, Item, isMacro) { - var dp, elem, value, e, yr, prefix, i, ilen, num; - var variable = this.variables[0]; - var macroFlag = "empty"; - if (isMacro) { - macroFlag = "macro-with-date"; - } - dp = Item[variable]; - if ("undefined" === typeof dp) { - dp = {"date-parts": [[0]] }; - if (!dp.year) { - state.tmp.empty_date = true; - } - } - if ("undefined" === typeof this.dateparts) { - this.dateparts = ["year", "month", "day"]; - } - if (dp.raw) { - dp = state.fun.dateparser.parse(dp.raw); - } else if (dp["date-parts"]) { - dp = state.dateParseArray(dp); - } - if ("undefined" === typeof dp) { - dp = {}; - } - for (i = 0, ilen = CSL.DATE_PARTS_INTERNAL.length; i < ilen; i += 1) { - elem = CSL.DATE_PARTS_INTERNAL[i]; - value = 0; - e = elem; - if (e.slice(-4) === "_end") { - e = e.slice(0, -4); +CSL.evaluateLabel = function (node, state, Item, item) { + var myterm; + if ("locator" === node.strings.term) { + if (item && item.label) { + if (item.label === "sub verbo") { + myterm = "sub-verbo"; + } else { + myterm = item.label; + } } - if (dp[elem] && this.dateparts.indexOf(e) > -1) { - value = dp[elem]; + if (!myterm) { + myterm = "page"; } - if (elem.slice(0, 4) === "year") { - yr = CSL.Util.Dates[e].numeric(state, value); - prefix = "Y"; - if (yr[0] === "-") { - prefix = "X"; - yr = yr.slice(1); - yr = 9999 - parseInt(yr, 10); + } else { + myterm = node.strings.term; + } + var plural = node.strings.plural; + if (item && "number" === typeof item.force_pluralism) { + plural = item.force_pluralism; + } else if ("number" !== typeof plural) { + if ("locator" === node.strings.term) { + if (item && item.locator) { + if (state.opt.development_extensions.locator_parsing_for_plurals) { + if (!state.tmp.shadow_numbers.locator) { + state.processNumber(false, item, "locator", Item.type); + } + plural = state.tmp.shadow_numbers.locator.plural; + } else { + plural = CSL.evaluateStringPluralism(item.locator); + } } - state.output.append(CSL.Util.Dates[elem.slice(0, 4)].numeric(state, (prefix + yr)), macroFlag); + } else if (["page", "page-first"].indexOf(node.variables[0]) > -1) { + state.processNumber(false, Item, myterm, Item.type); + plural = state.tmp.shadow_numbers[myterm].plural; + myterm = state.tmp.shadow_numbers[myterm].label; } else { - value = CSL.Util.Dates[e]["numeric-leading-zeros"](state, value); - if (!value) { - value = "00"; + if (!state.tmp.shadow_numbers[myterm]) { + state.processNumber(false, Item, myterm, Item.type); } - state.output.append(value, macroFlag); + plural = state.tmp.shadow_numbers[myterm].plural; + } + if (node.decorations && state.opt.development_extensions.csl_reverse_lookup_support) { + node.decorations.reverse(); + node.decorations.push(["@showid","true", node.cslid]); + node.decorations.reverse(); } } + return CSL.castLabel(state, node, myterm, plural, CSL.TOLERANT); }; -CSL.Engine.prototype.dateParseArray = function (date_obj) { - var ret, field, dpos, ppos, dp, exts, llen, pos, len, pppos, lllen; - ret = {}; - for (field in date_obj) { - if (field === "date-parts") { - dp = date_obj["date-parts"]; - if (dp.length > 1) { - if (dp[0].length !== dp[1].length) { - CSL.error("CSL data error: element mismatch in date range input."); - } - } - exts = ["", "_end"]; - for (var i = 0, ilen = dp.length; i < ilen; i += 1) { - for (var j = 0, jlen = CSL.DATE_PARTS.length; j < jlen; j += 1) { - if ("undefined" === typeof dp[i][j]) { - ret[(CSL.DATE_PARTS[j] + exts[i])] = dp[i][j]; - } else { - ret[(CSL.DATE_PARTS[j] + exts[i])] = parseInt(dp[i][j], 10); - } - } - } - } else if (date_obj.hasOwnProperty(field)) { - if (field === "literal" && "object" === typeof date_obj.literal && "string" === typeof date_obj.literal.part) { - CSL.debug("Warning: fixing up weird literal date value"); - ret.literal = date_obj.literal.part; - } else { - ret[field] = date_obj[field]; +CSL.evaluateStringPluralism = function (str) { + if (str) { + var m = str.match(/(?:[0-9],\s*[0-9]|\s+and\s+|&|([0-9]+)\s*[\-\u2013]\s*([0-9]+))/); + if (m && (!m[1] || parseInt(m[1], 10) < parseInt(m[2], 10))) { + return 1; + } + } + return 0; +}; +CSL.castLabel = function (state, node, term, plural, mode) { + var label_form = node.strings.form; + if (state.tmp.group_context.value()[5]) { + label_form = state.tmp.group_context.value()[5]; + } + var ret = state.getTerm(term, label_form, plural, false, mode); + if (state.tmp.strip_periods) { + ret = ret.replace(/\./g, ""); + } else { + for (var i = 0, ilen = node.decorations.length; i < ilen; i += 1) { + if ("@strip-periods" === node.decorations[i][0] && "true" === node.decorations[i][1]) { + ret = ret.replace(/\./g, ""); + break; } } } @@ -8833,13 +8760,12 @@ CSL.Attributes["@disambiguate"] = function (state, arg) { this.tests.push(func); } }; -CSL.Attributes["@is-numeric"] = function (state, arg) { +CSL.Attributes["@is-numeric"] = function (state, arg, joiner) { var variables = arg.split(/\s+/); var reverses = CSL.Util.setReverseConditions.call(this, variables); var maketest = function(variable, reverse) { return function (Item, item) { var myitem = Item; - var mytests = []; if (["locator","locator-revision"].indexOf(variable) > -1) { myitem = item; } @@ -8860,18 +8786,9 @@ CSL.Attributes["@is-numeric"] = function (state, arg) { return reverse ? true : false; } } - var mytests = []; for (var i=0; i<variables.length; i+=1) { - mytests.push(maketest(variables[i], reverses[i])); + this.rawtests.push(maketest(variables[i], reverses[i])); } - var func = state.fun.match[this.match](this, state, mytests, CSL.CONDITION_LEVEL_BOTTOM); - this.tests.push(func); -}; -CSL.Attributes["@is-numeric-any"] = function (state, arg) { - CSL.Attributes["@is-numeric"].call(this, state, arg, "any"); -}; -CSL.Attributes["@is-numeric-all"] = function (state, arg) { - CSL.Attributes["@is-numeric"].call(this, state, arg, "all"); }; CSL.Attributes["@is-uncertain-date"] = function (state, arg) { var variables = arg.split(/\s+/); @@ -8885,18 +8802,9 @@ CSL.Attributes["@is-uncertain-date"] = function (state, arg) { } } } - var mytests = []; for (var i=0,ilen=variables.length;i<ilen;i+=1) { - mytests.push(maketest(variables[i], reverses[i])); + this.rawtests.push(maketest(variables[i], reverses[i])); }; - var func = state.fun.match[this.match](this, state, mytests, CSL.CONDITION_LEVEL_BOTTOM); - this.tests.push(func); -}; -CSL.Attributes["@is-uncertain-date-any"] = function (state, arg) { - CSL.Attributes["@is-uncertain-date"].call(this, state, arg, "any"); -}; -CSL.Attributes["@is-uncertain-date-all"] = function (state, arg) { - CSL.Attributes["@is-uncertain-date"].call(this, state, arg, "all"); }; CSL.Attributes["@locator"] = function (state, arg) { var trylabels = arg.replace("sub verbo", "sub-verbo"); @@ -8919,18 +8827,9 @@ CSL.Attributes["@locator"] = function (state, arg) { } } } - var mytests = []; for (var i=0,ilen=trylabels.length;i<ilen;i+=1) { - mytests.push(maketest(trylabels[i], reverses[i])); + this.rawtests.push(maketest(trylabels[i], reverses[i])); } - var func = state.fun.match[this.match](this, state, mytests, CSL.CONDITION_LEVEL_BOTTOM); - this.tests.push(func); -}; -CSL.Attributes["@locator-any"] = function (state, arg) { - CSL.Attributes["@locator"].call(this, state, arg, "any"); -}; -CSL.Attributes["@locator-all"] = function (state, arg) { - CSL.Attributes["@locator"].call(this, state, arg, "all"); }; CSL.Attributes["@position"] = function (state, arg) { var tryposition; @@ -8957,7 +8856,6 @@ CSL.Attributes["@position"] = function (state, arg) { return false; } } - var mytests = []; for (var i=0,ilen=trypositions.length;i<ilen;i+=1) { var tryposition = trypositions[i]; if (tryposition === "first") { @@ -8970,18 +8868,16 @@ CSL.Attributes["@position"] = function (state, arg) { tryposition = CSL.POSITION_IBID_WITH_LOCATOR; } if ("near-note" === tryposition) { - mytests.push(function (Item, item) { + this.rawtests.push(function (Item, item) { if (item && item.position === CSL.POSITION_SUBSEQUENT && item["near-note"]) { return true; } return false; }); } else { - mytests.push(maketest(tryposition)); + this.rawtests.push(maketest(tryposition)); } } - var func = state.fun.match[this.match](this, state, mytests, CSL.CONDITION_LEVEL_BOTTOM); - this.tests.push(func); }; CSL.Attributes["@type"] = function (state, arg) { var types = arg.split(/\s+/); @@ -8996,20 +8892,12 @@ CSL.Attributes["@type"] = function (state, arg) { } } } - var mytests = []; for (var i=0,ilen=types.length;i<ilen;i+=1) { - mytests.push(maketest(types[i], reverses[i])); + this.rawtests.push(maketest(types[i], reverses[i])); } - var func = state.fun.match[this.match](this, state, mytests, CSL.CONDITION_LEVEL_BOTTOM); - this.tests.push(func); -}; -CSL.Attributes["@type-any"] = function (state, arg) { - CSL.Attributes["@type"].call(this, state, arg, "any"); -}; -CSL.Attributes["@type-all"] = function (state, arg) { - CSL.Attributes["@type"].call(this, state, arg, "all"); }; CSL.Attributes["@variable"] = function (state, arg) { + var func; this.variables = arg.split(/\s+/); this.variables_real = this.variables.slice(); if ("label" === this.name && this.variables[0]) { @@ -9155,20 +9043,11 @@ CSL.Attributes["@variable"] = function (state, arg) { return reverse ? true : false; } } - var mytests = []; for (var i=0,ilen=this.variables.length;i<ilen;i+=1) { - mytests.push(maketest(this.variables[i], reverses[i])); + this.rawtests.push(maketest(this.variables[i], reverses[i])); } - var func = state.fun.match[this.match](this, state, mytests, CSL.CONDITION_LEVEL_BOTTOM); - this.tests.push(func); } }; -CSL.Attributes["@variable-any"] = function (state, arg) { - CSL.Attributes["@variable"].call(this, state, arg, "any"); -}; -CSL.Attributes["@variable-all"] = function (state, arg) { - CSL.Attributes["@variable"].call(this, state, arg, "all"); -}; CSL.Attributes["@page"] = function (state, arg) { var trylabels = arg.replace("sub verbo", "sub-verbo"); trylabels = trylabels.split(/\s+/); @@ -9191,18 +9070,9 @@ CSL.Attributes["@page"] = function (state, arg) { } } } - var mytests = []; for (var i=0,ilen=trylabels.length;i<ilen;i+=1) { - mytests.push(maketest(trylabels[i], reverses[i])); + this.rawtests.push(maketest(trylabels[i], reverses[i])); } - var func = state.fun.match[this.match](this, state, mytests, CSL.CONDITION_LEVEL_BOTTOM); - this.tests.push(func); -}; -CSL.Attributes["@page-any"] = function (state, arg) { - CSL.Attributes["@page"].call(this, state, arg, "any"); -}; -CSL.Attributes["@page-all"] = function (state, arg) { - CSL.Attributes["@page"].call(this, state, arg, "all"); }; CSL.Attributes["@jurisdiction"] = function (state, arg) { var tryjurisdictions = arg.split(/\s+/); @@ -9229,19 +9099,10 @@ CSL.Attributes["@jurisdiction"] = function (state, arg) { return reverse ? true : false; } } - var mytests = []; for (var i=0,ilen=tryjurisdictions.length;i<ilen;i+=1) { var tryjurisdictionSlice = tryjurisdictions[i].slice(); - mytests.push(maketests(tryjurisdictionSlice, reverses[i])); + this.rawtests.push(maketests(tryjurisdictionSlice, reverses[i])); } - var func = state.fun.match[this.match](this, state, mytests, CSL.CONDITION_LEVEL_BOTTOM); - this.tests.push(func); -}; -CSL.Attributes["@jurisdiction-any"] = function (state, arg) { - CSL.Attributes["@jurisdiction"].call(this, state, arg, "any"); -}; -CSL.Attributes["@jurisdiction-all"] = function (state, arg) { - CSL.Attributes["@jurisdiction"].call(this, state, arg, "all"); }; CSL.Attributes["@context"] = function (state, arg) { var func = function (Item, item) { @@ -9265,12 +9126,9 @@ CSL.Attributes["@has-year-only"] = function (state, arg) { } } } - var mytests = []; for (var i=0,ilen=trydates.length;i<ilen;i+=1) { - mytests.push(maketest(trydates[i])); + this.rawtests.push(maketest(trydates[i])); } - var func = state.fun.match[this.match](this, state, mytests); - this.tests.push(func); }; CSL.Attributes["@has-month-or-season-only"] = function (state, arg) { var trydates = arg.split(/\s+/); @@ -9284,12 +9142,9 @@ CSL.Attributes["@has-month-or-season-only"] = function (state, arg) { } } } - var mytests = []; for (var i=0,ilen=trydates.length;i<ilen;i+=1) { - mytests.push(maketest(trydates[i])); + this.rawtests.push(maketest(trydates[i])); } - var func = state.fun.match[this.match](this, state, mytests); - this.tests.push(func); }; CSL.Attributes["@has-day-only"] = function (state, arg) { var trydates = arg.split(/\s+/); @@ -9303,12 +9158,9 @@ CSL.Attributes["@has-day-only"] = function (state, arg) { } } } - var mytests = []; for (var i=0,ilen=trydates.length;i<ilen;i+=1) { - mytests.push(maketest(trydates[i])); + this.rawtests.push(maketest(trydates[i])); }; - var func = state.fun.match[this.match](this, state, mytests); - this.tests.push(func); }; CSL.Attributes["@subjurisdictions"] = function (state, arg) { var trysubjurisdictions = parseInt(arg, 10); @@ -9806,21 +9658,7 @@ CSL.Attributes["@reverse-order"] = function (state, arg) { } }; CSL.Attributes["@display"] = function (state, arg) { - this.strings.cls = arg; -}; -var XML_PARSING; -if ("undefined" !== typeof CSL_IS_NODEJS) { - XML_PARSING = CSL_NODEJS; -} else if ("undefined" !== typeof CSL_E4X) { - XML_PARSING = CSL_E4X; -} else if ("undefined" !== typeof CSL_JSON) { - XML_PARSING = CSL_JSON; -} else { - XML_PARSING = CSL_CHROME; -} -CSL.System = {}; -CSL.System.Xml = { - "Parsing": XML_PARSING + this.strings.cls = arg; }; CSL.Stack = function (val, literal) { this.mystack = []; @@ -9857,848 +9695,848 @@ CSL.Stack.prototype.value = function () { CSL.Stack.prototype.length = function () { return this.mystack.length; }; -CSL.Util = { - setReverseConditions: function (lst) { - reverses = []; - for (var i=0,ilen=lst.length;i<ilen;i+=1) { - if (lst[i].slice(0,4) === "not:") { - lst[i] = lst[i].slice(4); - reverses.push(true); - } else { - reverses.push(false); - } +CSL.Parallel = function (state) { + this.state = state; + this.sets = new CSL.Stack([]); + this.try_cite = true; + this.use_parallels = false; + this.midVars = ["section", "volume", "container-title", "collection-number", "issue", "page-first", "page", "number"]; + this.ignoreVarsLawGeneral = ["first-reference-note-number", "locator", "label","page-first","page","genre"]; + this.ignoreVarsOrders = ["first-reference-note-number"]; + this.ignoreVarsOther = ["first-reference-note-number", "locator", "label","section","page-first","page"]; +}; +CSL.Parallel.prototype.isMid = function (variable) { + return (this.midVars.indexOf(variable) > -1); +}; +CSL.Parallel.prototype.StartCitation = function (sortedItems, out) { + this.parallel_conditional_blobs_list = []; + if (this.use_parallels) { + this.sortedItems = sortedItems; + this.sortedItemsPos = -1; + this.sets.clear(); + this.sets.push([]); + this.in_series = true; + this.delim_counter = 0; + this.delim_pointers = []; + if (out) { + this.out = out; + } else { + this.out = this.state.output.queue; } - return reverses; + this.master_was_neutral_cite = true; } }; -CSL.Util.Match = function () { - this.any = function (token, state, tests, level) { - return function (Item, item) { - for (var i=0, ilen=tests.length; i < ilen; i += 1) { - result = tests[i](Item, item); - if (result) { - return true; - } - } - return false; - }; - }; - this[undefined] = this.any; - this.none = function (token, state, tests, level) { - if (CSL.CONDITION_LEVEL_TOP !== level) { - return this.any(token, state, tests, level); +CSL.Parallel.prototype.StartCite = function (Item, item, prevItemID) { + var position, len, pos, x, curr, master, last_id, prev_locator, curr_locator, is_master, parallel; + if (["treaty"].indexOf(Item.type) > -1) { + this.ignoreVars = this.ignoreVarsOrders; + } else if (["article-journal","article-magazine"].indexOf(Item.type) > -1) { + this.ignoreVars = this.ignoreVarsOther; + } else { + this.ignoreVars = this.ignoreVarsLawGeneral; + } + if (this.use_parallels) { + if (this.sets.value().length && this.sets.value()[0].itemId == Item.id) { + this.ComposeSet(); } - return function (Item, item) { - for (var i=0,ilen=tests.length;i<ilen;i+=1) { - result = tests[i](Item,item); - if (result) { - return false; - } + this.sortedItemsPos += 1; + if (item) { + position = item.position; + } + this.try_cite = true; + var has_required_var = false; + for (var i = 0, ilen = CSL.PARALLEL_MATCH_VARS.length; i < ilen; i += 1) { + if (Item[CSL.PARALLEL_MATCH_VARS[i]]) { + has_required_var = true; + break; } - return true; - }; - }; - this.all = function (token, state, tests, level) { - return function (Item, item) { - for (var i=0,ilen=tests.length;i<ilen;i+=1) { - result = tests[i](Item,item); - if (!result) { - return false; + } + var basics_ok = true; + var last_cite = this.sets.value().slice(-1)[0]; + if (last_cite && last_cite.Item) { + if (last_cite.Item.title !== Item.title) { + basics_ok = false; + } else if (last_cite.Item.type !== Item.type) { + basics_ok = false; + } else if (["article-journal","article-magazine"].indexOf(Item.type) > -1) { + if (!this.state.opt.development_extensions.handle_parallel_articles + || last_cite.Item["container-title"] !== Item["container-title"]) { + basics_ok = false; } } - return true; - }; - }; -}; -CSL.Transform = function (state) { - var debug = false, abbreviations, token, fieldname, abbrev_family, opt; - this.abbrevs = {}; - this.abbrevs["default"] = new state.sys.AbbreviationSegments(); - this.getTextSubField = getTextSubField; - function abbreviate(state, Item, altvar, basevalue, myabbrev_family, use_field) { - var value; - if (!myabbrev_family) { - return basevalue; - } - var variable = myabbrev_family; - if (CSL.NUMERIC_VARIABLES.indexOf(myabbrev_family) > -1) { - myabbrev_family = "number"; - } - if (["publisher-place", "event-place", "jurisdiction", "archive-place"].indexOf(myabbrev_family) > -1) { - myabbrev_family = "place"; - } - if (["publisher", "authority"].indexOf(myabbrev_family) > -1) { - myabbrev_family = "institution-part"; } - if (["genre", "event", "medium", "title-short"].indexOf(myabbrev_family) > -1) { - myabbrev_family = "title"; - } - if (["archive"].indexOf(myabbrev_family) > -1) { - myabbrev_family = "collection-title"; + if (!basics_ok || !has_required_var || CSL.PARALLEL_TYPES.indexOf(Item.type) === -1) { + this.try_cite = true; + if (this.in_series) { + this.in_series = false; + } } - value = ""; - if (state.sys.getAbbreviation) { - var jurisdiction = state.transform.loadAbbreviation(Item.jurisdiction, myabbrev_family, basevalue); - if (state.transform.abbrevs[jurisdiction][myabbrev_family] && basevalue && state.sys.getAbbreviation) { - if (state.transform.abbrevs[jurisdiction][myabbrev_family][basevalue]) { - value = state.transform.abbrevs[jurisdiction][myabbrev_family][basevalue]; + this.cite = {}; + this.cite.front = []; + this.cite.mid = []; + this.cite.back = []; + this.cite.front_collapse = {}; + this.cite.back_forceme = []; + this.cite.position = position; + this.cite.Item = Item; + this.cite.itemId = "" + Item.id; + this.cite.prevItemID = "" + prevItemID; + this.target = "front"; + if (this.sortedItems && this.sortedItemsPos > 0 && this.sortedItemsPos < this.sortedItems.length) { + curr = this.sortedItems[this.sortedItemsPos][1]; + last_id = "" + this.sortedItems[(this.sortedItemsPos - 1)][1].id; + master = this.state.registry.registry[last_id].parallel; + prev_locator = false; + if (master == curr.id) { + len = this.sortedItemsPos - 1; + for (pos = len; pos > -1; pos += -1) { + if (this.sortedItems[pos][1].id == Item.id) { + prev_locator = this.sortedItems[pos][1].locator; + break; + } + } + curr_locator = this.sortedItems[this.sortedItemsPos][1].locator; + if (!prev_locator && curr_locator) { + curr.position = CSL.POSITION_IBID_WITH_LOCATOR; + } else if (curr_locator === prev_locator) { + curr.position = CSL.POSITION_IBID; + } else { + curr.position = CSL.POSITION_IBID_WITH_LOCATOR; } } + } else if (this.state.registry.registry[Item.id]) { + this.state.registry.registry[Item.id].parallel = false; + } else { + this.try_cite = false; + this.force_collapse = false; + return; } - if (!value && Item.type !== 'legal_case' && altvar && Item[altvar] && use_field) { - value = Item[altvar]; - } - if (!value) { - value = basevalue; + this.force_collapse = false; + if (this.state.registry.registry[Item.id].parallel) { + this.force_collapse = true; } - if (value && value.slice(0, 10) === "!here>>>") { - if (variable === "jurisdiction" && ["treaty", "patent"].indexOf(variable) > -1) { - value = value.slice(10); - } else { - value = false; - } - } - return value; } - function getFieldLocale(Item,field) { - var ret = state.opt["default-locale"][0].slice(0, 2) - var localeRex; - if (state.opt.development_extensions.strict_text_case_locales) { - localeRex = new RegExp("^([a-zA-Z]{2})(?:$|-.*| .*)"); +}; +CSL.Parallel.prototype.StartVariable = function (variable, real_variable) { + if (this.use_parallels && (this.try_cite || this.force_collapse)) { + if (variable === "names") { + this.variable = variable + ":" + this.target; } else { - localeRex = new RegExp("^([a-zA-Z]{2})(?:$|-.*|.*)"); - } - if (Item.language) { - m = ("" + Item.language).match(localeRex); - if (m) { - ret = m[1]; - } else { - ret = "tlh"; - } + this.variable = variable; } - if (Item.multi && Item.multi && Item.multi.main && Item.multi.main[field]) { - ret = Item.multi.main[field]; + if (this.ignoreVars.indexOf(variable) > -1) { + return; } - if (!state.opt.development_extensions.strict_text_case_locales - || state.opt.development_extensions.normalize_lang_keys_to_lowercase) { - ret = ret.toLowerCase(); + if (variable === "container-title" && this.sets.value().length === 0) { + this.master_was_neutral_cite = false; } - return ret; - }; - function getTextSubField(Item, field, locale_type, use_default, stopOrig) { - var m, lst, opt, o, oo, pos, key, ret, len, myret, opts; - var usedOrig = stopOrig; - if (!Item[field]) { - return {name:"", usedOrig:stopOrig}; + this.data = {}; + this.data.value = ""; + this.data.blobs = []; + var is_mid = this.isMid(variable); + if (real_variable === "authority" && this.variable === "names:front") { + this.try_cite = true; + this.in_series = false; + } else if (this.target === "front" && is_mid) { + this.target = "mid"; + } else if (this.target === "mid" && !is_mid && this.cite.Item.title && variable !== "names") { + this.target = "back"; + } else if (this.target === "back" && is_mid) { + this.try_cite = true; + this.in_series = false; } - ret = {name:"", usedOrig:stopOrig,locale:getFieldLocale(Item,field)}; - opts = state.opt[locale_type]; - if (locale_type === 'locale-orig') { - if (stopOrig) { - ret = {name:"", usedOrig:stopOrig}; + if (variable === "number") { + this.cite.front.push(this.variable); + } else if (CSL.PARALLEL_COLLAPSING_MID_VARSET.indexOf(variable) > -1) { + if (["article-journal","article-magazine"].indexOf(this.cite.Item.type) > -1) { + this.cite.mid.push(this.variable); } else { - ret = {name:Item[field], usedOrig:false, locale:getFieldLocale(Item,field)}; + this.cite.front.push(this.variable); } - return ret; - } else if (use_default && ("undefined" === typeof opts || opts.length === 0)) { - return {name:Item[field], usedOrig:true, locale:getFieldLocale(Item,field)}; + } else { + this.cite[this.target].push(this.variable); } - for (var i = 0, ilen = opts.length; i < ilen; i += 1) { - opt = opts[i]; - o = opt.split(/[\-_]/)[0]; - if (opt && Item.multi && Item.multi._keys[field] && Item.multi._keys[field][opt]) { - ret.name = Item.multi._keys[field][opt]; - ret.locale = o; - break; - } else if (o && Item.multi && Item.multi._keys[field] && Item.multi._keys[field][o]) { - ret.name = Item.multi._keys[field][o]; - ret.locale = o; - break; + } +}; +CSL.Parallel.prototype.AppendBlobPointer = function (blob) { + if (this.ignoreVars.indexOf(this.variable) > -1) { + return; + } + if (this.use_parallels && (this.force_collapse || this.try_cite)) { + if (["article-journal", "article-magazine"].indexOf(this.cite.Item.type) > -1) { + if (["volume","page","page-first","issue"].indexOf(this.variable) > -1) { + return; + } + if ("container-title" === this.variable && this.cite.mid.length > 1) { + return; } } - if (!ret.name && use_default) { - ret = {name:Item[field], usedOrig:true, locale:getFieldLocale(Item,field)}; + if (this.variable && (this.try_cite || this.force_collapse) && blob && blob.blobs) { + this.data.blobs.push([blob, blob.blobs.length]); } - return ret; } - function loadAbbreviation(jurisdiction, category, orig) { - var pos, len; - if (!jurisdiction) { - jurisdiction = "default"; - } - if (!orig) { - if (!this.abbrevs[jurisdiction]) { - this.abbrevs[jurisdiction] = new state.sys.AbbreviationSegments(); +}; +CSL.Parallel.prototype.AppendToVariable = function (str, varname) { + if (this.ignoreVars.indexOf(this.variable) > -1) { + return; + } + if (this.use_parallels && (this.try_cite || this.force_collapse)) { + if (this.target !== "back" || true) { + this.data.value += "::" + str; + } else { + var prev = this.sets.value()[(this.sets.value().length - 1)]; + if (prev) { + if (prev[this.variable]) { + if (prev[this.variable].value) { + this.data.value += "::" + str; + } + } } - return jurisdiction; } - if (state.sys.getAbbreviation) { - var tryList = ['default']; - if (jurisdiction !== 'default') { - var workLst = jurisdiction.split(/\s*;\s*/); - for (var i=0, ilen=workLst.length; i < ilen; i += 1) { - tryList.push(workLst.slice(0,i+1).join(';')); + } +}; +CSL.Parallel.prototype.CloseVariable = function () { + if (this.ignoreVars.indexOf(this.variable) > -1) { + return; + } + if (this.use_parallels && (this.try_cite || this.force_collapse)) { + this.cite[this.variable] = this.data; + if (this.sets.value().length > 0) { + var prev = this.sets.value()[(this.sets.value().length - 1)]; + if (this.target === "front" && this.variable === "issued") { + if (this.data.value && this.master_was_neutral_cite) { + this.target = "mid"; } } - for (var i=tryList.length - 1; i > -1; i += -1) { - if (!this.abbrevs[tryList[i]]) { - this.abbrevs[tryList[i]] = new state.sys.AbbreviationSegments(); + if (this.target === "front") { + if ((prev[this.variable] || this.data.value) && (!prev[this.variable] || this.data.value !== prev[this.variable].value)) { + if ("issued" !== this.variable) { + this.in_series = false; + } } - if (!this.abbrevs[tryList[i]][category][orig]) { - state.sys.getAbbreviation(state.opt.styleID, this.abbrevs, tryList[i], category, orig); + } else if (this.target === "mid") { + if (CSL.PARALLEL_COLLAPSING_MID_VARSET.indexOf(this.variable) > -1) { + if (prev[this.variable]) { + if (prev[this.variable].value === this.data.value) { + this.cite.front_collapse[this.variable] = true; + } else { + this.cite.front_collapse[this.variable] = false; + } + } else { + this.cite.front_collapse[this.variable] = false; + } } - if (this.abbrevs[tryList[i]][category][orig]) { - if (i < tryList.length) { - this.abbrevs[jurisdiction][category][orig] = this.abbrevs[tryList[i]][category][orig]; + } else if (this.target === "back") { + if (prev[this.variable]) { + if (this.data.value !== prev[this.variable].value + && this.sets.value().slice(-1)[0].back_forceme.indexOf(this.variable) === -1) { + this.in_series = false; } - break; } } } - return jurisdiction; } - this.loadAbbreviation = loadAbbreviation; - function publisherCheck (tok, Item, primary, myabbrev_family) { - var varname = tok.variables[0]; - if (state.publisherOutput && primary) { - if (["publisher","publisher-place"].indexOf(varname) === -1) { - return false; - } else { - state.publisherOutput[varname + "-token"] = tok; - state.publisherOutput.varlist.push(varname); - var lst = primary.split(/;\s*/); - if (lst.length === state.publisherOutput[varname + "-list"].length) { - state.publisherOutput[varname + "-list"] = lst; - } - for (var i = 0, ilen = lst.length; i < ilen; i += 1) { - lst[i] = abbreviate(state, Item, false, lst[i], myabbrev_family, true); - } - state.tmp[varname + "-token"] = tok; - return true; - } + this.variable = false; +}; +CSL.Parallel.prototype.CloseCite = function () { + var x, pos, len, has_issued, use_journal_info, volume_pos, container_title_pos, section_pos; + if (this.use_parallels && (this.force_collapse || this.try_cite)) { + use_journal_info = false; + if (!this.cite.front_collapse["container-title"]) { + use_journal_info = true; } - return false; - } - function getOutputFunction(variables, myabbrev_family, abbreviation_fallback, alternative_varname, transform_fallback) { - var localesets; - var langPrefs = CSL.LangPrefsMap[variables[0]]; - if (!langPrefs) { - localesets = false; - } else { - localesets = state.opt['cite-lang-prefs'][langPrefs]; + if (this.cite.front_collapse.volume === false) { + use_journal_info = true; } - return function (state, Item, item, usedOrig) { - var primary, primary_locale, secondary, secondary_locale, tertiary, tertiary_locale, primary_tok, group_tok, key; - if (!variables[0] || (!Item[variables[0]] && !Item[alternative_varname])) { - return null; - } - var slot = {primary:false, secondary:false, tertiary:false}; - if (state.tmp.area.slice(-5) === "_sort") { - slot.primary = 'locale-sort'; - } else { - if (localesets) { - var slotnames = ["primary", "secondary", "tertiary"]; - for (var i = 0, ilen = slotnames.length; i < ilen; i += 1) { - if (localesets.length - 1 < i) { - break; - } - if (localesets[i]) { - slot[slotnames[i]] = 'locale-' + localesets[i]; - } - } - } else { - slot.primary = 'locale-orig'; - } - } - if ((state.tmp.area !== "bibliography" - && !(state.tmp.area === "citation" - && state.opt.xclass === "note" - && item && !item.position))) { - slot.secondary = false; - slot.tertiary = false; - } - if (state.tmp["publisher-list"]) { - if (variables[0] === "publisher") { - state.tmp["publisher-token"] = this; - } else if (variables[0] === "publisher-place") { - state.tmp["publisher-place-token"] = this; - } - return null; - } - var res = getTextSubField(Item, variables[0], slot.primary, true); - primary = res.name; - primary_locale = res.locale; - var primaryUsedOrig = res.usedOrig; - if (publisherCheck(this, Item, primary, myabbrev_family)) { - return null; - } - secondary = false; - tertiary = false; - if (slot.secondary) { - res = getTextSubField(Item, variables[0], slot.secondary, false, res.usedOrig); - secondary = res.name; - secondary_locale = res.locale; + if (this.cite.front_collapse["collection-number"] === false) { + use_journal_info = true; + } + if (this.cite.front_collapse.section === false) { + use_journal_info = true; + } + if (use_journal_info) { + this.cite.use_journal_info = true; + section_pos = this.cite.front.indexOf("section"); + if (section_pos > -1) { + this.cite.front = this.cite.front.slice(0,section_pos).concat(this.cite.front.slice(section_pos + 1)); } - if (slot.tertiary) { - res = getTextSubField(Item, variables[0], slot.tertiary, false, res.usedOrig); - tertiary = res.name; - tertiary_locale = res.locale; + volume_pos = this.cite.front.indexOf("volume"); + if (volume_pos > -1) { + this.cite.front = this.cite.front.slice(0,volume_pos).concat(this.cite.front.slice(volume_pos + 1)); } - if (myabbrev_family) { - primary = abbreviate(state, Item, alternative_varname, primary, myabbrev_family, true); - if (primary) { - primary = quashCheck(primary); - } - secondary = abbreviate(state, Item, false, secondary, myabbrev_family, true); - tertiary = abbreviate(state, Item, false, tertiary, myabbrev_family, true); + container_title_pos = this.cite.front.indexOf("container-title"); + if (container_title_pos > -1) { + this.cite.front = this.cite.front.slice(0,container_title_pos).concat(this.cite.front.slice(container_title_pos + 1)); } - if ("demote" === this["leading-noise-words"]) { - primary = CSL.demoteNoiseWords(state, primary); - secondary = CSL.demoteNoiseWords(state, secondary); - tertiary = CSL.demoteNoiseWords(state, tertiary); + collection_number_pos = this.cite.front.indexOf("collection-number"); + if (collection_number_pos > -1) { + this.cite.front = this.cite.front.slice(0,collection_number_pos).concat(this.cite.front.slice(collection_number_pos + 1)); } - var template_tok = CSL.Util.cloneToken(this); - var primary_tok = CSL.Util.cloneToken(this); - var primaryPrefix; - if (slot.primary === "locale-translit") { - primaryPrefix = state.opt.citeAffixes[langPrefs][slot.primary].prefix; - } - if (primaryPrefix === "<i>" && variables[0] === 'title' && !primaryUsedOrig) { - var hasItalic = false; - for (var i = 0, ilen = primary_tok.decorations.length; i < ilen; i += 1) { - if (primary_tok.decorations[i][0] === "@font-style" - && primary_tok.decorations[i][1] === "italic") { - hasItalic = true; - } + } + if (!this.in_series && !this.force_collapse) { + this.ComposeSet(true); + } + if (this.sets.value().length === 0) { + has_date = false; + for (pos = 0, len = this.cite.back.length; pos < len; pos += 1) { + x = this.cite.back[pos]; + if (x === "issued" && this.cite["issued"] && this.cite["issued"].value) { + has_date = true; + break; } - if (!hasItalic) { - primary_tok.decorations.push(["@font-style", "italic"]) + } + if (!has_date) { + this.cite.back_forceme.push("issued"); + } + } else { + var idx = this.cite.front.indexOf("issued"); + if (idx === -1 || this.master_was_neutral_cite) { + this.cite.back_forceme = this.sets.value().slice(-1)[0].back_forceme; + } + if (idx > -1) { + var prev = this.sets.value()[this.sets.value().length - 1]; + if (!prev["issued"]) { + this.cite.front = this.cite.front.slice(0, idx).concat(this.cite.front.slice(idx + 1)); } } - if (primary_locale !== "en" && primary_tok.strings["text-case"] === "title") { - primary_tok.strings["text-case"] = "passthrough"; + if (this.master_was_neutral_cite && this.cite.mid.indexOf("names:mid") > -1) { + this.cite.front.push("names:mid"); } - if (secondary || tertiary) { - state.output.openLevel("empty"); - primary_tok.strings.suffix = ""; - state.output.append(primary, primary_tok); - if (secondary) { - secondary_tok = CSL.Util.cloneToken(template_tok); - secondary_tok.strings.prefix = state.opt.citeAffixes[langPrefs][slot.secondary].prefix; - secondary_tok.strings.suffix = state.opt.citeAffixes[langPrefs][slot.secondary].suffix; - if (!secondary_tok.strings.prefix) { - secondary_tok.strings.prefix = " "; - } - for (var i = secondary_tok.decorations.length - 1; i > -1; i += -1) { - if (['@quotes/true','@font-style/italic','@font-style/oblique','@font-weight/bold'].indexOf(secondary_tok.decorations[i].join('/')) > -1) { - secondary_tok.decorations = secondary_tok.decorations.slice(0, i).concat(secondary_tok.decorations.slice(i + 1)) - } - } - if (secondary_locale !== "en" && secondary_tok.strings["text-case"] === "title") { - secondary_tok.strings["text-case"] = "passthrough"; - } - state.output.append(secondary, secondary_tok); - var blob_obj = state.output.current.value(); - var blobs_pos = state.output.current.value().blobs.length - 1; - if (state.parallel.use_parallels) { - state.parallel.cite.front.push(variables[0] + ":secondary"); - state.parallel.cite[variables[0] + ":secondary"] = {blobs:[[blob_obj, blobs_pos]]}; + } + this.sets.value().push(this.cite); + } +}; +CSL.Parallel.prototype.ComposeSet = function (next_output_in_progress) { + var cite, pos, master, len; + if (this.use_parallels && (this.force_collapse || this.try_cite)) { + var lengthCheck = this.sets.value().length; + if (this.sets.value().length === 1) { + if (!this.in_series) { + this.sets.value().pop(); + this.delim_counter += 1; + } + } else { + len = this.sets.value().length; + for (pos = 0; pos < len; pos += 1) { + cite = this.sets.value()[pos]; + if (pos === 0) { + this.delim_counter += 1; + } else { + if (!cite.Item.title && cite.use_journal_info) { + this.delim_pointers.push(false); + } else { + this.delim_pointers.push(this.delim_counter); } + this.delim_counter += 1; } - if (tertiary) { - tertiary_tok = CSL.Util.cloneToken(template_tok); - tertiary_tok.strings.prefix = state.opt.citeAffixes[langPrefs][slot.tertiary].prefix; - tertiary_tok.strings.suffix = state.opt.citeAffixes[langPrefs][slot.tertiary].suffix; - if (!tertiary_tok.strings.prefix) { - tertiary_tok.strings.prefix = " "; - } - for (var i = tertiary_tok.decorations.length - 1; i > -1; i += -1) { - if (['@quotes/true','@font-style/italic','@font-style/oblique','@font-weight/bold'].indexOf(tertiary_tok.decorations[i].join('/')) > -1) { - tertiary_tok.decorations = tertiary_tok.decorations.slice(0, i).concat(tertiary_tok.decorations.slice(i + 1)) + if (CSL.POSITION_FIRST === cite.position) { + if (pos === 0) { + this.state.registry.registry[cite.itemId].master = true; + this.state.registry.registry[cite.itemId].siblings = []; + this.state.registry.registry[cite.itemId].parallel = false; + } else { + if (cite.prevItemID) { + if (!this.state.registry.registry[cite.prevItemID].parallel) { + this.state.registry.registry[cite.itemId].parallel = cite.prevItemID; + } else { + this.state.registry.registry[cite.itemId].parallel = this.state.registry.registry[cite.prevItemID].parallel; + } + this.state.registry.registry[cite.itemId].siblings = this.state.registry.registry[cite.prevItemID].siblings; + if (!this.state.registry.registry[cite.itemId].siblings) { + this.state.registry.registry[cite.itemId].siblings = []; + CSL.debug("WARNING: adding missing siblings array to registry object"); + } + this.state.registry.registry[cite.itemId].siblings.push(cite.itemId); } } - if (tertiary_locale !== "en" && tertiary_tok.strings["text-case"] === "title") { - tertiary_tok.strings["text-case"] = "passthrough"; - } - state.output.append(tertiary, tertiary_tok); - var blob_obj = state.output.current.value(); - var blobs_pos = state.output.current.value().blobs.length - 1; - if (state.parallel.use_parallels) { - state.parallel.cite.front.push(variables[0] + ":tertiary"); - state.parallel.cite[variables[0] + ":tertiary"] = {blobs:[[blob_obj, blobs_pos]]}; - } } - state.output.closeLevel(); - } else { - state.output.append(primary, primary_tok); } - return null; - }; + this.sets.push([]); + } + if (lengthCheck < 2) { + this.purgeGroupsIfParallel(false); + } else { + this.purgeGroupsIfParallel(true); + } + this.in_series = true; } - this.getOutputFunction = getOutputFunction; - function quashCheck(value) { - var m = value.match(/^!([-,_a-z]+)>>>/); - if (m) { - var fields = m[1].split(","); - value = value.slice(m[0].length); - for (var i = 0, ilen = fields.length; i < ilen; i += 1) { - if (state.tmp.done_vars.indexOf(fields[i]) === -1) { - state.tmp.done_vars.push(fields[i]); +}; +CSL.Parallel.prototype.PruneOutputQueue = function () { + var len, pos, series, ppos, llen, cite; + if (this.use_parallels) { + len = this.sets.mystack.length; + for (pos = 0; pos < len; pos += 1) { + series = this.sets.mystack[pos]; + if (series.length > 1) { + llen = series.length; + for (ppos = 0; ppos < llen; ppos += 1) { + cite = series[ppos]; + if (ppos === 0) { + this.purgeVariableBlobs(cite, cite.back); + } else if (ppos === (series.length - 1)) { + this.purgeVariableBlobs(cite, cite.front.concat(cite.back_forceme)); + } else { + this.purgeVariableBlobs(cite, cite.front.concat(cite.back)); + } } } } - return value; } - this.quashCheck = quashCheck; -}; -CSL.Parallel = function (state) { - this.state = state; - this.sets = new CSL.Stack([]); - this.try_cite = true; - this.use_parallels = false; - this.midVars = ["section", "volume", "container-title", "collection-number", "issue", "page-first", "page", "number"]; - this.ignoreVarsLawGeneral = ["first-reference-note-number", "locator", "label","page-first","page","genre"]; - this.ignoreVarsOrders = ["first-reference-note-number"]; - this.ignoreVarsOther = ["first-reference-note-number", "locator", "label","section","page-first","page"]; -}; -CSL.Parallel.prototype.isMid = function (variable) { - return (this.midVars.indexOf(variable) > -1); }; -CSL.Parallel.prototype.StartCitation = function (sortedItems, out) { - this.parallel_conditional_blobs_list = []; +CSL.Parallel.prototype.purgeVariableBlobs = function (cite, varnames) { + var len, pos, varname, b, llen, ppos, out; if (this.use_parallels) { - this.sortedItems = sortedItems; - this.sortedItemsPos = -1; - this.sets.clear(); - this.sets.push([]); - this.in_series = true; - this.delim_counter = 0; - this.delim_pointers = []; - if (out) { - this.out = out; - } else { - this.out = this.state.output.queue; + out = this.state.output.current.value(); + if ("undefined" === typeof out.length) { + out = out.blobs; + } + for (pos = 0, len = this.delim_pointers.length; pos < len; pos += 1) { + ppos = this.delim_pointers[pos]; + if (ppos !== false) { + out[ppos].parallel_delimiter = ", "; + } + } + len = varnames.length - 1; + for (pos = len; pos > -1; pos += -1) { + varname = varnames[pos]; + if (cite[varname]) { + llen = cite[varname].blobs.length - 1; + for (ppos = llen; ppos > -1; ppos += -1) { + b = cite[varname].blobs[ppos]; + b[0].blobs = b[0].blobs.slice(0, b[1]).concat(b[0].blobs.slice((b[1] + 1))); + this.state.tmp.has_purged_parallel = true; + if (b[0] && b[0].strings && "string" == typeof b[0].strings.oops + && b[0].parent && b[0].parent) { + b[0].parent.parent.strings.delimiter = b[0].strings.oops; + } + } + } } - this.master_was_neutral_cite = true; } }; -CSL.Parallel.prototype.StartCite = function (Item, item, prevItemID) { - var position, len, pos, x, curr, master, last_id, prev_locator, curr_locator, is_master, parallel; - if (["treaty"].indexOf(Item.type) > -1) { - this.ignoreVars = this.ignoreVarsOrders; - } else if (["article-journal","article-magazine"].indexOf(Item.type) > -1) { - this.ignoreVars = this.ignoreVarsOther; - } else { - this.ignoreVars = this.ignoreVarsLawGeneral; - } - if (this.use_parallels) { - if (this.sets.value().length && this.sets.value()[0].itemId == Item.id) { - this.ComposeSet(); +CSL.Parallel.prototype.purgeGroupsIfParallel = function (original_condition) { + for (var i = this.parallel_conditional_blobs_list.length - 1; i > -1; i += -1) { + var obj = this.parallel_conditional_blobs_list[i]; + var purgeme = true; + for (var j = 0, jlen = obj.conditions.length; j < jlen; j += 1) { + if (!(!obj.conditions[j] === !!original_condition + || ("master" === obj.conditions[j] + && !this.state.registry.registry[obj.id].master) + || ("servant" === obj.conditions[j] + && !this.state.registry.registry[obj.id].parallel))) { + var purgeme = false; + break; + } } - this.sortedItemsPos += 1; - if (item) { - position = item.position; + if (purgeme) { + var buffer = []; + while (obj.blobs.length > obj.pos) { + buffer.push(obj.blobs.pop()); + } + if (buffer.length) { + buffer.pop(); + } + while (buffer.length) { + obj.blobs.push(buffer.pop()); + } } - this.try_cite = true; - var has_required_var = false; - for (var i = 0, ilen = CSL.PARALLEL_MATCH_VARS.length; i < ilen; i += 1) { - if (Item[CSL.PARALLEL_MATCH_VARS[i]]) { - has_required_var = true; - break; + this.parallel_conditional_blobs_list.pop(); + } +} +CSL.Util = { + setReverseConditions: function (lst) { + reverses = []; + for (var i=0,ilen=lst.length;i<ilen;i+=1) { + if (lst[i].slice(0,4) === "not:") { + lst[i] = lst[i].slice(4); + reverses.push(true); + } else { + reverses.push(false); } } - var basics_ok = true; - var last_cite = this.sets.value().slice(-1)[0]; - if (last_cite && last_cite.Item) { - if (last_cite.Item.title !== Item.title) { - basics_ok = false; - } else if (last_cite.Item.type !== Item.type) { - basics_ok = false; - } else if (["article-journal","article-magazine"].indexOf(Item.type) > -1) { - if (!this.state.opt.development_extensions.handle_parallel_articles - || last_cite.Item["container-title"] !== Item["container-title"]) { - basics_ok = false; + return reverses; + } +}; +CSL.Util.Match = function () { + this.any = function (token, state, tests, level) { + return function (Item, item) { + for (var i=0, ilen=tests.length; i < ilen; i += 1) { + result = tests[i](Item, item); + if (result) { + return true; } } + return false; + }; + }; + this[undefined] = this.any; + this.none = function (token, state, tests, level) { + if (CSL.CONDITION_LEVEL_TOP !== level) { + return this.any(token, state, tests, level); } - if (!basics_ok || !has_required_var || CSL.PARALLEL_TYPES.indexOf(Item.type) === -1) { - this.try_cite = true; - if (this.in_series) { - this.in_series = false; - } - } - this.cite = {}; - this.cite.front = []; - this.cite.mid = []; - this.cite.back = []; - this.cite.front_collapse = {}; - this.cite.back_forceme = []; - this.cite.position = position; - this.cite.Item = Item; - this.cite.itemId = "" + Item.id; - this.cite.prevItemID = "" + prevItemID; - this.target = "front"; - if (this.sortedItems && this.sortedItemsPos > 0 && this.sortedItemsPos < this.sortedItems.length) { - curr = this.sortedItems[this.sortedItemsPos][1]; - last_id = "" + this.sortedItems[(this.sortedItemsPos - 1)][1].id; - master = this.state.registry.registry[last_id].parallel; - prev_locator = false; - if (master == curr.id) { - len = this.sortedItemsPos - 1; - for (pos = len; pos > -1; pos += -1) { - if (this.sortedItems[pos][1].id == Item.id) { - prev_locator = this.sortedItems[pos][1].locator; - break; - } + return function (Item, item) { + for (var i=0,ilen=tests.length;i<ilen;i+=1) { + result = tests[i](Item,item); + if (result) { + return false; } - curr_locator = this.sortedItems[this.sortedItemsPos][1].locator; - if (!prev_locator && curr_locator) { - curr.position = CSL.POSITION_IBID_WITH_LOCATOR; - } else if (curr_locator === prev_locator) { - curr.position = CSL.POSITION_IBID; - } else { - curr.position = CSL.POSITION_IBID_WITH_LOCATOR; + } + return true; + }; + }; + this.all = function (token, state, tests, level) { + return function (Item, item) { + for (var i=0,ilen=tests.length;i<ilen;i+=1) { + result = tests[i](Item,item); + if (!result) { + return false; } } - } else if (this.state.registry.registry[Item.id]) { - this.state.registry.registry[Item.id].parallel = false; - } else { - this.try_cite = false; - this.force_collapse = false; - return; + return true; + }; + }; +}; +CSL.Transform = function (state) { + var debug = false, abbreviations, token, fieldname, abbrev_family, opt; + this.abbrevs = {}; + this.abbrevs["default"] = new state.sys.AbbreviationSegments(); + this.getTextSubField = getTextSubField; + function abbreviate(state, Item, altvar, basevalue, myabbrev_family, use_field) { + var value; + if (!myabbrev_family) { + return basevalue; } - this.force_collapse = false; - if (this.state.registry.registry[Item.id].parallel) { - this.force_collapse = true; + var variable = myabbrev_family; + if (CSL.NUMERIC_VARIABLES.indexOf(myabbrev_family) > -1) { + myabbrev_family = "number"; } - } -}; -CSL.Parallel.prototype.StartVariable = function (variable, real_variable) { - if (this.use_parallels && (this.try_cite || this.force_collapse)) { - if (variable === "names") { - this.variable = variable + ":" + this.target; - } else { - this.variable = variable; + if (["publisher-place", "event-place", "jurisdiction", "archive-place"].indexOf(myabbrev_family) > -1) { + myabbrev_family = "place"; } - if (this.ignoreVars.indexOf(variable) > -1) { - return; + if (["publisher", "authority"].indexOf(myabbrev_family) > -1) { + myabbrev_family = "institution-part"; } - if (variable === "container-title" && this.sets.value().length === 0) { - this.master_was_neutral_cite = false; + if (["genre", "event", "medium", "title-short"].indexOf(myabbrev_family) > -1) { + myabbrev_family = "title"; } - this.data = {}; - this.data.value = ""; - this.data.blobs = []; - var is_mid = this.isMid(variable); - if (real_variable === "authority" && this.variable === "names:front") { - this.try_cite = true; - this.in_series = false; - } else if (this.target === "front" && is_mid) { - this.target = "mid"; - } else if (this.target === "mid" && !is_mid && this.cite.Item.title && variable !== "names") { - this.target = "back"; - } else if (this.target === "back" && is_mid) { - this.try_cite = true; - this.in_series = false; + if (["archive"].indexOf(myabbrev_family) > -1) { + myabbrev_family = "collection-title"; } - if (variable === "number") { - this.cite.front.push(this.variable); - } else if (CSL.PARALLEL_COLLAPSING_MID_VARSET.indexOf(variable) > -1) { - if (["article-journal","article-magazine"].indexOf(this.cite.Item.type) > -1) { - this.cite.mid.push(this.variable); + value = ""; + if (state.sys.getAbbreviation) { + var jurisdiction = state.transform.loadAbbreviation(Item.jurisdiction, myabbrev_family, basevalue); + if (state.transform.abbrevs[jurisdiction][myabbrev_family] && basevalue && state.sys.getAbbreviation) { + if (state.transform.abbrevs[jurisdiction][myabbrev_family][basevalue]) { + value = state.transform.abbrevs[jurisdiction][myabbrev_family][basevalue]; + } + } + } + if (!value && Item.type !== 'legal_case' && altvar && Item[altvar] && use_field) { + value = Item[altvar]; + } + if (!value) { + value = basevalue; + } + if (value && value.slice(0, 10) === "!here>>>") { + if (variable === "jurisdiction" && ["treaty", "patent"].indexOf(variable) > -1) { + value = value.slice(10); } else { - this.cite.front.push(this.variable); + value = false; } + } + return value; + } + function getFieldLocale(Item,field) { + var ret = state.opt["default-locale"][0].slice(0, 2) + var localeRex; + if (state.opt.development_extensions.strict_text_case_locales) { + localeRex = new RegExp("^([a-zA-Z]{2})(?:$|-.*| .*)"); } else { - this.cite[this.target].push(this.variable); + localeRex = new RegExp("^([a-zA-Z]{2})(?:$|-.*|.*)"); } - } -}; -CSL.Parallel.prototype.AppendBlobPointer = function (blob) { - if (this.ignoreVars.indexOf(this.variable) > -1) { - return; - } - if (this.use_parallels && (this.force_collapse || this.try_cite)) { - if (["article-journal", "article-magazine"].indexOf(this.cite.Item.type) > -1) { - if (["volume","page","page-first","issue"].indexOf(this.variable) > -1) { - return; - } - if ("container-title" === this.variable && this.cite.mid.length > 1) { - return; + if (Item.language) { + m = ("" + Item.language).match(localeRex); + if (m) { + ret = m[1]; + } else { + ret = "tlh"; } } - if (this.variable && (this.try_cite || this.force_collapse) && blob && blob.blobs) { - this.data.blobs.push([blob, blob.blobs.length]); + if (Item.multi && Item.multi && Item.multi.main && Item.multi.main[field]) { + ret = Item.multi.main[field]; } - } -}; -CSL.Parallel.prototype.AppendToVariable = function (str, varname) { - if (this.ignoreVars.indexOf(this.variable) > -1) { - return; - } - if (this.use_parallels && (this.try_cite || this.force_collapse)) { - if (this.target !== "back" || true) { - this.data.value += "::" + str; - } else { - var prev = this.sets.value()[(this.sets.value().length - 1)]; - if (prev) { - if (prev[this.variable]) { - if (prev[this.variable].value) { - this.data.value += "::" + str; - } - } + if (!state.opt.development_extensions.strict_text_case_locales + || state.opt.development_extensions.normalize_lang_keys_to_lowercase) { + ret = ret.toLowerCase(); + } + return ret; + }; + function getTextSubField(Item, field, locale_type, use_default, stopOrig) { + var m, lst, opt, o, oo, pos, key, ret, len, myret, opts; + var usedOrig = stopOrig; + if (!Item[field]) { + return {name:"", usedOrig:stopOrig}; + } + ret = {name:"", usedOrig:stopOrig,locale:getFieldLocale(Item,field)}; + opts = state.opt[locale_type]; + if (locale_type === 'locale-orig') { + if (stopOrig) { + ret = {name:"", usedOrig:stopOrig}; + } else { + ret = {name:Item[field], usedOrig:false, locale:getFieldLocale(Item,field)}; + } + return ret; + } else if (use_default && ("undefined" === typeof opts || opts.length === 0)) { + return {name:Item[field], usedOrig:true, locale:getFieldLocale(Item,field)}; + } + for (var i = 0, ilen = opts.length; i < ilen; i += 1) { + opt = opts[i]; + o = opt.split(/[\-_]/)[0]; + if (opt && Item.multi && Item.multi._keys[field] && Item.multi._keys[field][opt]) { + ret.name = Item.multi._keys[field][opt]; + ret.locale = o; + break; + } else if (o && Item.multi && Item.multi._keys[field] && Item.multi._keys[field][o]) { + ret.name = Item.multi._keys[field][o]; + ret.locale = o; + break; } } + if (!ret.name && use_default) { + ret = {name:Item[field], usedOrig:true, locale:getFieldLocale(Item,field)}; + } + return ret; } -}; -CSL.Parallel.prototype.CloseVariable = function () { - if (this.ignoreVars.indexOf(this.variable) > -1) { - return; - } - if (this.use_parallels && (this.try_cite || this.force_collapse)) { - this.cite[this.variable] = this.data; - if (this.sets.value().length > 0) { - var prev = this.sets.value()[(this.sets.value().length - 1)]; - if (this.target === "front" && this.variable === "issued") { - if (this.data.value && this.master_was_neutral_cite) { - this.target = "mid"; + function loadAbbreviation(jurisdiction, category, orig) { + var pos, len; + if (!jurisdiction) { + jurisdiction = "default"; + } + if (!orig) { + if (!this.abbrevs[jurisdiction]) { + this.abbrevs[jurisdiction] = new state.sys.AbbreviationSegments(); + } + return jurisdiction; + } + if (state.sys.getAbbreviation) { + var tryList = ['default']; + if (jurisdiction !== 'default') { + var workLst = jurisdiction.split(/\s*;\s*/); + for (var i=0, ilen=workLst.length; i < ilen; i += 1) { + tryList.push(workLst.slice(0,i+1).join(';')); } } - if (this.target === "front") { - if ((prev[this.variable] || this.data.value) && (!prev[this.variable] || this.data.value !== prev[this.variable].value)) { - if ("issued" !== this.variable) { - this.in_series = false; - } + for (var i=tryList.length - 1; i > -1; i += -1) { + if (!this.abbrevs[tryList[i]]) { + this.abbrevs[tryList[i]] = new state.sys.AbbreviationSegments(); } - } else if (this.target === "mid") { - if (CSL.PARALLEL_COLLAPSING_MID_VARSET.indexOf(this.variable) > -1) { - if (prev[this.variable]) { - if (prev[this.variable].value === this.data.value) { - this.cite.front_collapse[this.variable] = true; - } else { - this.cite.front_collapse[this.variable] = false; - } - } else { - this.cite.front_collapse[this.variable] = false; - } + if (!this.abbrevs[tryList[i]][category][orig]) { + state.sys.getAbbreviation(state.opt.styleID, this.abbrevs, tryList[i], category, orig); } - } else if (this.target === "back") { - if (prev[this.variable]) { - if (this.data.value !== prev[this.variable].value - && this.sets.value().slice(-1)[0].back_forceme.indexOf(this.variable) === -1) { - this.in_series = false; + if (this.abbrevs[tryList[i]][category][orig]) { + if (i < tryList.length) { + this.abbrevs[jurisdiction][category][orig] = this.abbrevs[tryList[i]][category][orig]; } + break; } } } + return jurisdiction; } - this.variable = false; -}; -CSL.Parallel.prototype.CloseCite = function () { - var x, pos, len, has_issued, use_journal_info, volume_pos, container_title_pos, section_pos; - if (this.use_parallels && (this.force_collapse || this.try_cite)) { - use_journal_info = false; - if (!this.cite.front_collapse["container-title"]) { - use_journal_info = true; - } - if (this.cite.front_collapse.volume === false) { - use_journal_info = true; - } - if (this.cite.front_collapse["collection-number"] === false) { - use_journal_info = true; + this.loadAbbreviation = loadAbbreviation; + function publisherCheck (tok, Item, primary, myabbrev_family) { + var varname = tok.variables[0]; + if (state.publisherOutput && primary) { + if (["publisher","publisher-place"].indexOf(varname) === -1) { + return false; + } else { + state.publisherOutput[varname + "-token"] = tok; + state.publisherOutput.varlist.push(varname); + var lst = primary.split(/;\s*/); + if (lst.length === state.publisherOutput[varname + "-list"].length) { + state.publisherOutput[varname + "-list"] = lst; + } + for (var i = 0, ilen = lst.length; i < ilen; i += 1) { + lst[i] = abbreviate(state, Item, false, lst[i], myabbrev_family, true); + } + state.tmp[varname + "-token"] = tok; + return true; + } } - if (this.cite.front_collapse.section === false) { - use_journal_info = true; + return false; + } + function getOutputFunction(variables, myabbrev_family, abbreviation_fallback, alternative_varname, transform_fallback) { + var localesets; + var langPrefs = CSL.LangPrefsMap[variables[0]]; + if (!langPrefs) { + localesets = false; + } else { + localesets = state.opt['cite-lang-prefs'][langPrefs]; } - if (use_journal_info) { - this.cite.use_journal_info = true; - section_pos = this.cite.front.indexOf("section"); - if (section_pos > -1) { - this.cite.front = this.cite.front.slice(0,section_pos).concat(this.cite.front.slice(section_pos + 1)); - } - volume_pos = this.cite.front.indexOf("volume"); - if (volume_pos > -1) { - this.cite.front = this.cite.front.slice(0,volume_pos).concat(this.cite.front.slice(volume_pos + 1)); + return function (state, Item, item, usedOrig) { + var primary, primary_locale, secondary, secondary_locale, tertiary, tertiary_locale, primary_tok, group_tok, key; + if (!variables[0] || (!Item[variables[0]] && !Item[alternative_varname])) { + return null; } - container_title_pos = this.cite.front.indexOf("container-title"); - if (container_title_pos > -1) { - this.cite.front = this.cite.front.slice(0,container_title_pos).concat(this.cite.front.slice(container_title_pos + 1)); + var slot = {primary:false, secondary:false, tertiary:false}; + if (state.tmp.area.slice(-5) === "_sort") { + slot.primary = 'locale-sort'; + } else { + if (localesets) { + var slotnames = ["primary", "secondary", "tertiary"]; + for (var i = 0, ilen = slotnames.length; i < ilen; i += 1) { + if (localesets.length - 1 < i) { + break; + } + if (localesets[i]) { + slot[slotnames[i]] = 'locale-' + localesets[i]; + } + } + } else { + slot.primary = 'locale-orig'; + } } - collection_number_pos = this.cite.front.indexOf("collection-number"); - if (collection_number_pos > -1) { - this.cite.front = this.cite.front.slice(0,collection_number_pos).concat(this.cite.front.slice(collection_number_pos + 1)); + if ((state.tmp.area !== "bibliography" + && !(state.tmp.area === "citation" + && state.opt.xclass === "note" + && item && !item.position))) { + slot.secondary = false; + slot.tertiary = false; } - } - if (!this.in_series && !this.force_collapse) { - this.ComposeSet(true); - } - if (this.sets.value().length === 0) { - has_date = false; - for (pos = 0, len = this.cite.back.length; pos < len; pos += 1) { - x = this.cite.back[pos]; - if (x === "issued" && this.cite["issued"] && this.cite["issued"].value) { - has_date = true; - break; + if (state.tmp["publisher-list"]) { + if (variables[0] === "publisher") { + state.tmp["publisher-token"] = this; + } else if (variables[0] === "publisher-place") { + state.tmp["publisher-place-token"] = this; } + return null; } - if (!has_date) { - this.cite.back_forceme.push("issued"); + var res = getTextSubField(Item, variables[0], slot.primary, true); + primary = res.name; + primary_locale = res.locale; + var primaryUsedOrig = res.usedOrig; + if (publisherCheck(this, Item, primary, myabbrev_family)) { + return null; } - } else { - var idx = this.cite.front.indexOf("issued"); - if (idx === -1 || this.master_was_neutral_cite) { - this.cite.back_forceme = this.sets.value().slice(-1)[0].back_forceme; + secondary = false; + tertiary = false; + if (slot.secondary) { + res = getTextSubField(Item, variables[0], slot.secondary, false, res.usedOrig); + secondary = res.name; + secondary_locale = res.locale; } - if (idx > -1) { - var prev = this.sets.value()[this.sets.value().length - 1]; - if (!prev["issued"]) { - this.cite.front = this.cite.front.slice(0, idx).concat(this.cite.front.slice(idx + 1)); + if (slot.tertiary) { + res = getTextSubField(Item, variables[0], slot.tertiary, false, res.usedOrig); + tertiary = res.name; + tertiary_locale = res.locale; + } + if (myabbrev_family) { + primary = abbreviate(state, Item, alternative_varname, primary, myabbrev_family, true); + if (primary) { + primary = quashCheck(primary); } + secondary = abbreviate(state, Item, false, secondary, myabbrev_family, true); + tertiary = abbreviate(state, Item, false, tertiary, myabbrev_family, true); } - if (this.master_was_neutral_cite && this.cite.mid.indexOf("names:mid") > -1) { - this.cite.front.push("names:mid"); + if ("demote" === this["leading-noise-words"]) { + primary = CSL.demoteNoiseWords(state, primary); + secondary = CSL.demoteNoiseWords(state, secondary); + tertiary = CSL.demoteNoiseWords(state, tertiary); } - } - this.sets.value().push(this.cite); - } -}; -CSL.Parallel.prototype.ComposeSet = function (next_output_in_progress) { - var cite, pos, master, len; - if (this.use_parallels && (this.force_collapse || this.try_cite)) { - var lengthCheck = this.sets.value().length; - if (this.sets.value().length === 1) { - if (!this.in_series) { - this.sets.value().pop(); - this.delim_counter += 1; + var template_tok = CSL.Util.cloneToken(this); + var primary_tok = CSL.Util.cloneToken(this); + var primaryPrefix; + if (slot.primary === "locale-translit") { + primaryPrefix = state.opt.citeAffixes[langPrefs][slot.primary].prefix; + } + if (primaryPrefix === "<i>" && variables[0] === 'title' && !primaryUsedOrig) { + var hasItalic = false; + for (var i = 0, ilen = primary_tok.decorations.length; i < ilen; i += 1) { + if (primary_tok.decorations[i][0] === "@font-style" + && primary_tok.decorations[i][1] === "italic") { + hasItalic = true; + } + } + if (!hasItalic) { + primary_tok.decorations.push(["@font-style", "italic"]) + } } - } else { - len = this.sets.value().length; - for (pos = 0; pos < len; pos += 1) { - cite = this.sets.value()[pos]; - if (pos === 0) { - this.delim_counter += 1; - } else { - if (!cite.Item.title && cite.use_journal_info) { - this.delim_pointers.push(false); - } else { - this.delim_pointers.push(this.delim_counter); + if (primary_locale !== "en" && primary_tok.strings["text-case"] === "title") { + primary_tok.strings["text-case"] = "passthrough"; + } + if (secondary || tertiary) { + state.output.openLevel("empty"); + primary_tok.strings.suffix = ""; + state.output.append(primary, primary_tok); + if (secondary) { + secondary_tok = CSL.Util.cloneToken(template_tok); + secondary_tok.strings.prefix = state.opt.citeAffixes[langPrefs][slot.secondary].prefix; + secondary_tok.strings.suffix = state.opt.citeAffixes[langPrefs][slot.secondary].suffix; + if (!secondary_tok.strings.prefix) { + secondary_tok.strings.prefix = " "; } - this.delim_counter += 1; - } - if (CSL.POSITION_FIRST === cite.position) { - if (pos === 0) { - this.state.registry.registry[cite.itemId].master = true; - this.state.registry.registry[cite.itemId].siblings = []; - this.state.registry.registry[cite.itemId].parallel = false; - } else { - if (cite.prevItemID) { - if (!this.state.registry.registry[cite.prevItemID].parallel) { - this.state.registry.registry[cite.itemId].parallel = cite.prevItemID; - } else { - this.state.registry.registry[cite.itemId].parallel = this.state.registry.registry[cite.prevItemID].parallel; - } - this.state.registry.registry[cite.itemId].siblings = this.state.registry.registry[cite.prevItemID].siblings; - if (!this.state.registry.registry[cite.itemId].siblings) { - this.state.registry.registry[cite.itemId].siblings = []; - CSL.debug("WARNING: adding missing siblings array to registry object"); - } - this.state.registry.registry[cite.itemId].siblings.push(cite.itemId); + for (var i = secondary_tok.decorations.length - 1; i > -1; i += -1) { + if (['@quotes/true','@font-style/italic','@font-style/oblique','@font-weight/bold'].indexOf(secondary_tok.decorations[i].join('/')) > -1) { + secondary_tok.decorations = secondary_tok.decorations.slice(0, i).concat(secondary_tok.decorations.slice(i + 1)) } } + if (secondary_locale !== "en" && secondary_tok.strings["text-case"] === "title") { + secondary_tok.strings["text-case"] = "passthrough"; + } + state.output.append(secondary, secondary_tok); + var blob_obj = state.output.current.value(); + var blobs_pos = state.output.current.value().blobs.length - 1; + if (state.parallel.use_parallels) { + state.parallel.cite.front.push(variables[0] + ":secondary"); + state.parallel.cite[variables[0] + ":secondary"] = {blobs:[[blob_obj, blobs_pos]]}; + } } - } - this.sets.push([]); - } - if (lengthCheck < 2) { - this.purgeGroupsIfParallel(false); - } else { - this.purgeGroupsIfParallel(true); - } - this.in_series = true; - } -}; -CSL.Parallel.prototype.PruneOutputQueue = function () { - var len, pos, series, ppos, llen, cite; - if (this.use_parallels) { - len = this.sets.mystack.length; - for (pos = 0; pos < len; pos += 1) { - series = this.sets.mystack[pos]; - if (series.length > 1) { - llen = series.length; - for (ppos = 0; ppos < llen; ppos += 1) { - cite = series[ppos]; - if (ppos === 0) { - this.purgeVariableBlobs(cite, cite.back); - } else if (ppos === (series.length - 1)) { - this.purgeVariableBlobs(cite, cite.front.concat(cite.back_forceme)); - } else { - this.purgeVariableBlobs(cite, cite.front.concat(cite.back)); + if (tertiary) { + tertiary_tok = CSL.Util.cloneToken(template_tok); + tertiary_tok.strings.prefix = state.opt.citeAffixes[langPrefs][slot.tertiary].prefix; + tertiary_tok.strings.suffix = state.opt.citeAffixes[langPrefs][slot.tertiary].suffix; + if (!tertiary_tok.strings.prefix) { + tertiary_tok.strings.prefix = " "; + } + for (var i = tertiary_tok.decorations.length - 1; i > -1; i += -1) { + if (['@quotes/true','@font-style/italic','@font-style/oblique','@font-weight/bold'].indexOf(tertiary_tok.decorations[i].join('/')) > -1) { + tertiary_tok.decorations = tertiary_tok.decorations.slice(0, i).concat(tertiary_tok.decorations.slice(i + 1)) + } + } + if (tertiary_locale !== "en" && tertiary_tok.strings["text-case"] === "title") { + tertiary_tok.strings["text-case"] = "passthrough"; + } + state.output.append(tertiary, tertiary_tok); + var blob_obj = state.output.current.value(); + var blobs_pos = state.output.current.value().blobs.length - 1; + if (state.parallel.use_parallels) { + state.parallel.cite.front.push(variables[0] + ":tertiary"); + state.parallel.cite[variables[0] + ":tertiary"] = {blobs:[[blob_obj, blobs_pos]]}; } } + state.output.closeLevel(); + } else { + state.output.append(primary, primary_tok); } - } + return null; + }; } -}; -CSL.Parallel.prototype.purgeVariableBlobs = function (cite, varnames) { - var len, pos, varname, b, llen, ppos, out; - if (this.use_parallels) { - out = this.state.output.current.value(); - if ("undefined" === typeof out.length) { - out = out.blobs; - } - for (pos = 0, len = this.delim_pointers.length; pos < len; pos += 1) { - ppos = this.delim_pointers[pos]; - if (ppos !== false) { - out[ppos].parallel_delimiter = ", "; - } - } - len = varnames.length - 1; - for (pos = len; pos > -1; pos += -1) { - varname = varnames[pos]; - if (cite[varname]) { - llen = cite[varname].blobs.length - 1; - for (ppos = llen; ppos > -1; ppos += -1) { - b = cite[varname].blobs[ppos]; - b[0].blobs = b[0].blobs.slice(0, b[1]).concat(b[0].blobs.slice((b[1] + 1))); - this.state.tmp.has_purged_parallel = true; - if (b[0] && b[0].strings && "string" == typeof b[0].strings.oops - && b[0].parent && b[0].parent) { - b[0].parent.parent.strings.delimiter = b[0].strings.oops; - } + this.getOutputFunction = getOutputFunction; + function quashCheck(value) { + var m = value.match(/^!([-,_a-z]+)>>>/); + if (m) { + var fields = m[1].split(","); + value = value.slice(m[0].length); + for (var i = 0, ilen = fields.length; i < ilen; i += 1) { + if (state.tmp.done_vars.indexOf(fields[i]) === -1) { + state.tmp.done_vars.push(fields[i]); } } } + return value; } + this.quashCheck = quashCheck; }; -CSL.Parallel.prototype.purgeGroupsIfParallel = function (original_condition) { - for (var i = this.parallel_conditional_blobs_list.length - 1; i > -1; i += -1) { - var obj = this.parallel_conditional_blobs_list[i]; - var purgeme = true; - for (var j = 0, jlen = obj.conditions.length; j < jlen; j += 1) { - if (!(!obj.conditions[j] === !!original_condition - || ("master" === obj.conditions[j] - && !this.state.registry.registry[obj.id].master) - || ("servant" === obj.conditions[j] - && !this.state.registry.registry[obj.id].parallel))) { - var purgeme = false; - break; - } - } - if (purgeme) { - var buffer = []; - while (obj.blobs.length > obj.pos) { - buffer.push(obj.blobs.pop()); - } - if (buffer.length) { - buffer.pop(); - } - while (buffer.length) { - obj.blobs.push(buffer.pop()); - } - } - this.parallel_conditional_blobs_list.pop(); - } -} CSL.Token = function (name, tokentype) { this.name = name; this.strings = {}; @@ -10711,6 +10549,7 @@ CSL.Token = function (name, tokentype) { this.tokentype = tokentype; this.evaluator = false; this.tests = []; + this.rawtests = []; this.succeed = false; this.fail = false; this.next = false; @@ -10738,6 +10577,7 @@ CSL.Util.cloneToken = function (token) { if (token.execs) { newtok.execs = token.execs.slice(); newtok.tests = token.tests.slice(); + newtok.rawtests = token.tests.slice(); } return newtok; }; @@ -10935,6 +10775,94 @@ CSL.Util.fixDateNode = function (parent, pos, node) { } return this.sys.xml.insertChildNodeAfter(parent, node, pos, datexml); }; +CSL.dateMacroAsSortKey = function (state, Item) { + CSL.dateAsSortKey.call(this, state, Item, true); +}; +CSL.dateAsSortKey = function (state, Item, isMacro) { + var dp, elem, value, e, yr, prefix, i, ilen, num; + var variable = this.variables[0]; + var macroFlag = "empty"; + if (isMacro) { + macroFlag = "macro-with-date"; + } + dp = Item[variable]; + if ("undefined" === typeof dp) { + dp = {"date-parts": [[0]] }; + if (!dp.year) { + state.tmp.empty_date = true; + } + } + if ("undefined" === typeof this.dateparts) { + this.dateparts = ["year", "month", "day"]; + } + if (dp.raw) { + dp = state.fun.dateparser.parse(dp.raw); + } else if (dp["date-parts"]) { + dp = state.dateParseArray(dp); + } + if ("undefined" === typeof dp) { + dp = {}; + } + for (i = 0, ilen = CSL.DATE_PARTS_INTERNAL.length; i < ilen; i += 1) { + elem = CSL.DATE_PARTS_INTERNAL[i]; + value = 0; + e = elem; + if (e.slice(-4) === "_end") { + e = e.slice(0, -4); + } + if (dp[elem] && this.dateparts.indexOf(e) > -1) { + value = dp[elem]; + } + if (elem.slice(0, 4) === "year") { + yr = CSL.Util.Dates[e].numeric(state, value); + prefix = "Y"; + if (yr[0] === "-") { + prefix = "X"; + yr = yr.slice(1); + yr = 9999 - parseInt(yr, 10); + } + state.output.append(CSL.Util.Dates[elem.slice(0, 4)].numeric(state, (prefix + yr)), macroFlag); + } else { + value = CSL.Util.Dates[e]["numeric-leading-zeros"](state, value); + if (!value) { + value = "00"; + } + state.output.append(value, macroFlag); + } + } +}; +CSL.Engine.prototype.dateParseArray = function (date_obj) { + var ret, field, dpos, ppos, dp, exts, llen, pos, len, pppos, lllen; + ret = {}; + for (field in date_obj) { + if (field === "date-parts") { + dp = date_obj["date-parts"]; + if (dp.length > 1) { + if (dp[0].length !== dp[1].length) { + CSL.error("CSL data error: element mismatch in date range input."); + } + } + exts = ["", "_end"]; + for (var i = 0, ilen = dp.length; i < ilen; i += 1) { + for (var j = 0, jlen = CSL.DATE_PARTS.length; j < jlen; j += 1) { + if ("undefined" === typeof dp[i][j]) { + ret[(CSL.DATE_PARTS[j] + exts[i])] = dp[i][j]; + } else { + ret[(CSL.DATE_PARTS[j] + exts[i])] = parseInt(dp[i][j], 10); + } + } + } + } else if (date_obj.hasOwnProperty(field)) { + if (field === "literal" && "object" === typeof date_obj.literal && "string" === typeof date_obj.literal.part) { + CSL.debug("Warning: fixing up weird literal date value"); + ret.literal = date_obj.literal.part; + } else { + ret[field] = date_obj[field]; + } + } + } + return ret; +}; CSL.Util.Names = {}; CSL.Util.Names.compareNamesets = CSL.NameOutput.prototype._compareNamesets; CSL.Util.Names.unInitialize = function (state, name) { @@ -12931,12 +12859,13 @@ CSL.Registry.prototype.registerAmbigToken = function (akey, id, ambig_config) { var old_names_params = this.registry[id].disambig.names[i]; if (new_names_params !== old_names_params) { this.state.tmp.taintedItemIDs[id] = true; - } - for (var j=0,jlen=ambig_config.givens[i].length;j<jlen;j+=1) { - var new_gnames_params = ambig_config.givens[i][j]; - var old_gnames_params = this.registry[id].disambig.givens[i][j]; - if (new_gnames_params !== old_gnames_params) { - this.state.tmp.taintedItemIDs[id] = true; + } else { + for (var j=0,jlen=ambig_config.givens[i].length;j<jlen;j+=1) { + var new_gnames_params = ambig_config.givens[i][j]; + var old_gnames_params = this.registry[id].disambig.givens[i][j]; + if (new_gnames_params !== old_gnames_params) { + this.state.tmp.taintedItemIDs[id] = true; + } } } } @@ -13194,6 +13123,10 @@ CSL.Registry.NameReg = function (state) { this.delitems = delitems; this.evalname = evalname; }; +CSL.Registry.CitationReg = function (state) { + this.citationById = {}; + this.citationByIndex = []; +}; CSL.Disambiguation = function (state) { this.state = state; this.sys = this.state.sys; @@ -13555,7 +13488,3 @@ CSL.Disambiguation.prototype.captureStepToBase = function() { } this.betterbase.names[this.gnameset] = this.base.names[this.gnameset]; }; -CSL.Registry.CitationReg = function (state) { - this.citationById = {}; - this.citationByIndex = []; -};