3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
10 * Full author contact details are available in file CREDITS.
15 #include "BiblioInfo.h"
17 #include "BufferParams.h"
18 #include "buffer_funcs.h"
20 #include "InsetIterator.h"
22 #include "Paragraph.h"
23 #include "TextClass.h"
24 #include "TocBackend.h"
26 #include "support/convert.h"
27 #include "support/debug.h"
28 #include "support/docstream.h"
29 #include "support/gettext.h"
30 #include "support/lassert.h"
31 #include "support/lstrings.h"
32 #include "support/regex.h"
33 #include "support/textutils.h"
38 using namespace lyx::support;
45 // gets the "family name" from an author-type string
46 docstring familyName(docstring const & name)
51 // first we look for a comma, and take the last name to be everything
52 // preceding the right-most one, so that we also get the "jr" part.
53 docstring::size_type idx = name.rfind(',');
54 if (idx != docstring::npos)
55 return ltrim(name.substr(0, idx));
57 // OK, so now we want to look for the last name. We're going to
58 // include the "von" part. This isn't perfect.
59 // Split on spaces, to get various tokens.
60 vector<docstring> pieces = getVectorFromString(name, from_ascii(" "));
61 // If we only get two, assume the last one is the last name
62 if (pieces.size() <= 2)
65 // Now we look for the first token that begins with a lower case letter.
66 vector<docstring>::const_iterator it = pieces.begin();
67 vector<docstring>::const_iterator en = pieces.end();
68 for (; it != en; ++it) {
69 if ((*it).size() == 0)
71 char_type const c = (*it)[0];
76 if (it == en) // we never found a "von"
79 // reconstruct what we need to return
82 for (; it != en; ++it) {
92 // converts a string containing LaTeX commands into unicode
94 docstring convertLaTeXCommands(docstring const & str)
99 bool scanning_cmd = false;
100 bool scanning_math = false;
101 bool escaped = false; // used to catch \$, etc.
103 char_type const ch = val[0];
105 // if we're scanning math, we output everything until we
106 // find an unescaped $, at which point we break out.
113 scanning_math = false;
119 // if we're scanning a command name, then we just
120 // discard characters until we hit something that
123 if (isAlphaASCII(ch)) {
128 // so we're done with this command.
129 // now we fall through and check this character.
130 scanning_cmd = false;
133 // was the last character a \? If so, then this is something like:
134 // \\ or \$, so we'll just output it. That's probably not always right...
136 // exception: output \, as THIN SPACE
138 ret.push_back(0x2009);
149 scanning_math = true;
153 // we just ignore braces
154 if (ch == '{' || ch == '}') {
159 // we're going to check things that look like commands, so if
160 // this doesn't, just output it.
167 // ok, could be a command of some sort
168 // let's see if it corresponds to some unicode
169 // unicodesymbols has things in the form: \"{u},
170 // whereas we may see things like: \"u. So we'll
171 // look for that and change it, if necessary.
172 static lyx::regex const reg("^\\\\\\W\\w");
173 if (lyx::regex_search(to_utf8(val), reg)) {
174 val.insert(3, from_ascii("}"));
175 val.insert(2, from_ascii("{"));
178 docstring const cnvtd = Encodings::fromLaTeXCommand(val,
179 Encodings::TEXT_CMD, rem);
180 if (!cnvtd.empty()) {
181 // it did, so we'll take that bit and proceed with what's left
186 // it's a command of some sort
197 //////////////////////////////////////////////////////////////////////
201 //////////////////////////////////////////////////////////////////////
203 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
204 : is_bibtex_(true), bib_key_(key), entry_type_(type), info_(),
209 docstring const BibTeXInfo::getAbbreviatedAuthor(bool jurabib_style) const
212 docstring const opt = label();
217 docstring const remainder = trim(split(opt, authors, '('));
218 if (remainder.empty())
219 // in this case, we didn't find a "(",
220 // so we don't have author (year)
225 docstring author = convertLaTeXCommands(operator[]("author"));
226 if (author.empty()) {
227 author = convertLaTeXCommands(operator[]("editor"));
232 // FIXME Move this to a separate routine that can
233 // be called from elsewhere.
235 // OK, we've got some names. Let's format them.
236 // Try to split the author list on " and "
237 vector<docstring> const authors =
238 getVectorFromString(author, from_ascii(" and "));
240 if (jurabib_style && (authors.size() == 2 || authors.size() == 3)) {
241 docstring shortauthor = familyName(authors[0])
242 + "/" + familyName(authors[1]);
243 if (authors.size() == 3)
244 shortauthor += "/" + familyName(authors[2]);
248 if (authors.size() == 2)
249 return bformat(_("%1$s and %2$s"),
250 familyName(authors[0]), familyName(authors[1]));
252 if (authors.size() > 2)
253 return bformat(_("%1$s et al."), familyName(authors[0]));
255 return familyName(authors[0]);
259 docstring const BibTeXInfo::getYear() const
262 return operator[]("year");
264 docstring const opt = label();
269 docstring tmp = split(opt, authors, '(');
271 // we don't have author (year)
274 tmp = split(tmp, year, ')');
279 docstring const BibTeXInfo::getXRef() const
283 return operator[]("crossref");
288 string parseOptions(string const & format, string & optkey,
289 string & ifpart, string & elsepart);
291 // Calls parseOptions to deal with an embedded option, such as:
292 // {%number%[[, no.~%number%]]}
293 // which must appear at the start of format. ifelsepart gets the
294 // whole of the option, and we return what's left after the option.
295 // we return format if there is an error.
296 string parseEmbeddedOption(string const & format, string & ifelsepart)
298 LASSERT(format[0] == '{' && format[1] == '%', return format);
302 string const rest = parseOptions(format, optkey, ifpart, elsepart);
303 if (format == rest) { // parse error
304 LYXERR0("ERROR! Couldn't parse `" << format <<"'.");
307 LASSERT(rest.size() <= format.size(), /* */);
308 ifelsepart = format.substr(0, format.size() - rest.size());
313 // Gets a "clause" from a format string, where the clause is
314 // delimited by '[[' and ']]'. Returns what is left after the
315 // clause is removed, and returns format if there is an error.
316 string getClause(string const & format, string & clause)
321 // we'll remove characters from the front of fmt as we
324 if (fmt[0] == ']' && fmt.size() > 1 && fmt[1] == ']') {
329 // check for an embedded option
330 if (fmt[0] == '{' && fmt.size() > 1 && fmt[1] == '%') {
332 string const rest = parseEmbeddedOption(fmt, part);
334 LYXERR0("ERROR! Couldn't parse embedded option in `" << format <<"'.");
339 } else { // it's just a normal character
348 // parse an options string, which must appear at the start of the
349 // format parameter. puts the parsed bits in optkey, ifpart, and
350 // elsepart and returns what's left after the option is removed.
351 // if there's an error, it returns format itself.
352 string parseOptions(string const & format, string & optkey,
353 string & ifpart, string & elsepart)
355 LASSERT(format[0] == '{' && format[1] == '%', return format);
357 string fmt = format.substr(2);
358 size_t pos = fmt.find('%'); // end of key
359 if (pos == string::npos) {
360 LYXERR0("Error parsing `" << format <<"'. Can't find end of key.");
363 optkey = fmt.substr(0,pos);
364 fmt = fmt.substr(pos + 1);
365 // [[format]] should be next
366 if (fmt[0] != '[' || fmt[1] != '[') {
367 LYXERR0("Error parsing `" << format <<"'. Can't find '[[' after key.");
372 fmt = getClause(curfmt, ifpart);
374 LYXERR0("Error parsing `" << format <<"'. Couldn't get if clause.");
378 if (fmt[0] == '}') // we're done, no else clause
379 return fmt.substr(1);
381 // else part should follow
382 if (fmt[0] != '[' || fmt[1] != '[') {
383 LYXERR0("Error parsing `" << format <<"'. Can't find else clause.");
388 fmt = getClause(curfmt, elsepart);
390 if (fmt == curfmt || fmt[0] != '}') {
391 LYXERR0("Error parsing `" << format <<"'. Can't find end of option.");
394 return fmt.substr(1);
400 docstring BibTeXInfo::expandFormat(string const & format,
401 BibTeXInfo const * const xref, int & counter, Buffer const & buf,
402 bool richtext, docstring before, docstring after, docstring dialog, bool next) const
404 // incorrect use of macros could put us in an infinite loop
405 static int max_passes = 5000;
406 docstring ret; // return value
408 bool scanning_key = false;
409 bool scanning_rich = false;
411 CiteEngineType const engine_type = buf.params().citeEngineType();
413 // we'll remove characters from the front of fmt as we
416 if (counter++ > max_passes) {
417 LYXERR0("Recursion limit reached while parsing `"
422 char_type thischar = fmt[0];
423 if (thischar == '%') {
424 // beginning or end of key
427 scanning_key = false;
428 // so we replace the key with its value, which may be empty
431 // FIXME: instead of passing the buf, just past the macros
432 // FIXME: and the language code
434 buf.params().documentClass().getCiteMacro(engine_type, key);
435 fmt = val + fmt.substr(1);
437 } else if (key[0] == '_') {
438 // a translatable bit
440 buf.params().documentClass().getCiteMacro(engine_type, key);
441 docstring const trans =
442 translateIfPossible(from_utf8(val), buf.params().language->code());
445 docstring const val = getValueForKey(key, before, after, dialog, xref);
454 else if (thischar == '{') {
455 // beginning of option?
457 LYXERR0("ERROR: Found `{' when scanning key in `" << format << "'.");
460 if (fmt.size() > 1) {
462 // it is the beginning of an optional format
466 string const newfmt =
467 parseOptions(fmt, optkey, ifpart, elsepart);
468 if (newfmt == fmt) // parse error
471 docstring const val = getValueForKey(optkey, before, after, dialog, xref);
472 if (optkey == "next" && next)
473 ret += from_utf8(ifpart); // without expansion
474 else if (!val.empty())
475 ret += expandFormat(ifpart, xref, counter, buf,
476 richtext, before, after, dialog, next);
477 else if (!elsepart.empty())
478 ret += expandFormat(elsepart, xref, counter, buf,
479 richtext, before, after, dialog, next);
480 // fmt will have been shortened for us already
484 // beginning of rich text
485 scanning_rich = true;
490 // we are here if '{' was not followed by % or !.
491 // So it's just a character.
494 else if (scanning_rich && thischar == '!'
495 && fmt.size() > 1 && fmt[1] == '}') {
497 scanning_rich = false;
501 else if (scanning_key)
502 key += char(thischar);
507 // we need to escape '<' and '>'
510 else if (thischar == '>')
515 } else if (!scanning_rich /* && !richtext */)
517 // else the character is discarded, which will happen only if
518 // richtext == false and we are scanning rich text
522 LYXERR0("Never found end of key in `" << format << "'!");
526 LYXERR0("Never found end of rich text in `" << format << "'!");
533 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref,
534 Buffer const & buf, bool richtext) const
540 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
545 CiteEngineType const engine_type = buf.params().citeEngineType();
546 DocumentClass const & dc = buf.params().documentClass();
547 string const & format = dc.getCiteFormat(engine_type, to_utf8(entry_type_));
549 info_ = expandFormat(format, xref, counter, buf, richtext);
552 info_ = convertLaTeXCommands(info_);
557 docstring const BibTeXInfo::getLabel(BibTeXInfo const * const xref,
558 Buffer const & buf, string const & format, bool richtext,
559 docstring before, docstring after, docstring dialog, bool next) const
565 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
572 loclabel_ = expandFormat(format, xref, counter, buf, richtext,
573 before, after, dialog, next);
575 if (!loclabel_.empty())
576 loclabel_ = convertLaTeXCommands(loclabel_);
581 docstring const & BibTeXInfo::operator[](docstring const & field) const
583 BibTeXInfo::const_iterator it = find(field);
586 static docstring const empty_value = docstring();
591 docstring const & BibTeXInfo::operator[](string const & field) const
593 return operator[](from_ascii(field));
597 docstring BibTeXInfo::getValueForKey(string const & key,
598 docstring const & before, docstring const & after, docstring const & dialog,
599 BibTeXInfo const * const xref) const
601 docstring ret = operator[](key);
602 if (ret.empty() && xref)
607 // FIXME: dialog, textbefore and textafter have nothing to do with this
610 else if (key == "entrytype")
612 else if (key == "key")
614 else if (key == "label")
616 else if (key == "abbrvauthor")
617 // Special key to provide abbreviated author names.
618 return getAbbreviatedAuthor();
619 else if (key == "shortauthor")
620 // When shortauthor is not defined, jurabib automatically
621 // provides jurabib-style abbreviated author names. We do
623 return getAbbreviatedAuthor(true);
624 else if (key == "shorttitle") {
625 // When shorttitle is not defined, jurabib uses for `article'
626 // and `periodical' entries the form `journal volume [year]'
627 // and for other types of entries it uses the `title' field.
628 if (entry_type_ == "article" || entry_type_ == "periodical")
629 return operator[]("journal") + " " + operator[]("volume")
630 + " [" + operator[]("year") + "]";
632 return operator[]("title");
633 } else if (key == "textbefore")
635 else if (key == "textafter")
637 else if (key == "year")
643 //////////////////////////////////////////////////////////////////////
647 //////////////////////////////////////////////////////////////////////
650 // A functor for use with sort, leading to case insensitive sorting
651 class compareNoCase: public binary_function<docstring, docstring, bool>
654 bool operator()(docstring const & s1, docstring const & s2) const {
655 return compare_no_case(s1, s2) < 0;
661 vector<docstring> const BiblioInfo::getKeys() const
663 vector<docstring> bibkeys;
664 BiblioInfo::const_iterator it = begin();
665 for (; it != end(); ++it)
666 bibkeys.push_back(it->first);
667 sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
672 vector<docstring> const BiblioInfo::getFields() const
674 vector<docstring> bibfields;
675 set<docstring>::const_iterator it = field_names_.begin();
676 set<docstring>::const_iterator end = field_names_.end();
677 for (; it != end; ++it)
678 bibfields.push_back(*it);
679 sort(bibfields.begin(), bibfields.end());
684 vector<docstring> const BiblioInfo::getEntries() const
686 vector<docstring> bibentries;
687 set<docstring>::const_iterator it = entry_types_.begin();
688 set<docstring>::const_iterator end = entry_types_.end();
689 for (; it != end; ++it)
690 bibentries.push_back(*it);
691 sort(bibentries.begin(), bibentries.end());
696 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
698 BiblioInfo::const_iterator it = find(key);
701 BibTeXInfo const & data = it->second;
702 return data.getAbbreviatedAuthor();
706 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
708 BiblioInfo::const_iterator it = find(key);
711 BibTeXInfo const & data = it->second;
712 return data.citeNumber();
716 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier) const
718 BiblioInfo::const_iterator it = find(key);
721 BibTeXInfo const & data = it->second;
722 docstring year = data.getYear();
724 // let's try the crossref
725 docstring const xref = data.getXRef();
727 return _("No year"); // no luck
728 BiblioInfo::const_iterator const xrefit = find(xref);
730 return _("No year"); // no luck again
731 BibTeXInfo const & xref_data = xrefit->second;
732 year = xref_data.getYear();
734 if (use_modifier && data.modifier() != 0)
735 year += data.modifier();
740 docstring const BiblioInfo::getInfo(docstring const & key,
741 Buffer const & buf, bool richtext) const
743 BiblioInfo::const_iterator it = find(key);
745 return docstring(_("Bibliography entry not found!"));
746 BibTeXInfo const & data = it->second;
747 BibTeXInfo const * xrefptr = 0;
748 docstring const xref = data.getXRef();
750 BiblioInfo::const_iterator const xrefit = find(xref);
752 xrefptr = &(xrefit->second);
754 return data.getInfo(xrefptr, buf, richtext);
758 docstring const BiblioInfo::getLabel(vector<docstring> const & keys,
759 Buffer const & buf, string const & style, bool richtext,
760 docstring const & before, docstring const & after, docstring const & dialog) const
762 CiteEngineType const engine_type = buf.params().citeEngineType();
763 DocumentClass const & dc = buf.params().documentClass();
764 string const & format = dc.getCiteFormat(engine_type, style, "cite");
765 docstring ret = from_utf8(format);
766 vector<docstring>::const_iterator key = keys.begin();
767 vector<docstring>::const_iterator ken = keys.end();
768 for (; key != ken; ++key) {
769 BiblioInfo::const_iterator it = find(*key);
770 BibTeXInfo empty_data;
771 empty_data.key(*key);
772 BibTeXInfo & data = empty_data;
773 BibTeXInfo const * xrefptr = 0;
776 docstring const xref = data.getXRef();
778 BiblioInfo::const_iterator const xrefit = find(xref);
780 xrefptr = &(xrefit->second);
783 ret = data.getLabel(xrefptr, buf, to_utf8(ret), richtext,
784 before, after, dialog, key+1 != ken);
790 bool BiblioInfo::isBibtex(docstring const & key) const
792 BiblioInfo::const_iterator it = find(key);
795 return it->second.isBibTeX();
799 vector<docstring> const BiblioInfo::getCiteStrings(
800 vector<docstring> const & keys, vector<CitationStyle> const & styles,
801 Buffer const & buf, bool richtext, docstring const & before,
802 docstring const & after, docstring const & dialog) const
805 return vector<docstring>();
808 vector<docstring> vec(styles.size());
809 for (size_t i = 0; i != vec.size(); ++i) {
810 style = styles[i].cmd;
811 vec[i] = getLabel(keys, buf, style, richtext, before, after, dialog);
818 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
820 bimap_.insert(info.begin(), info.end());
821 field_names_.insert(info.field_names_.begin(), info.field_names_.end());
822 entry_types_.insert(info.entry_types_.begin(), info.entry_types_.end());
827 // used in xhtml to sort a list of BibTeXInfo objects
828 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
830 docstring const lauth = lhs->getAbbreviatedAuthor();
831 docstring const rauth = rhs->getAbbreviatedAuthor();
832 docstring const lyear = lhs->getYear();
833 docstring const ryear = rhs->getYear();
834 docstring const ltitl = lhs->operator[]("title");
835 docstring const rtitl = rhs->operator[]("title");
836 return (lauth < rauth)
837 || (lauth == rauth && lyear < ryear)
838 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
843 void BiblioInfo::collectCitedEntries(Buffer const & buf)
845 cited_entries_.clear();
846 // We are going to collect all the citation keys used in the document,
847 // getting them from the TOC.
848 // FIXME We may want to collect these differently, in the first case,
849 // so that we might have them in order of appearance.
850 set<docstring> citekeys;
851 Toc const & toc = buf.tocBackend().toc("citation");
852 Toc::const_iterator it = toc.begin();
853 Toc::const_iterator const en = toc.end();
854 for (; it != en; ++it) {
855 if (it->str().empty())
857 vector<docstring> const keys = getVectorFromString(it->str());
858 citekeys.insert(keys.begin(), keys.end());
860 if (citekeys.empty())
863 // We have a set of the keys used in this document.
864 // We will now convert it to a list of the BibTeXInfo objects used in
866 vector<BibTeXInfo const *> bi;
867 set<docstring>::const_iterator cit = citekeys.begin();
868 set<docstring>::const_iterator const cen = citekeys.end();
869 for (; cit != cen; ++cit) {
870 BiblioInfo::const_iterator const bt = find(*cit);
871 if (bt == end() || !bt->second.isBibTeX())
873 bi.push_back(&(bt->second));
876 sort(bi.begin(), bi.end(), lSorter);
878 // Now we can write the sorted keys
879 vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
880 vector<BibTeXInfo const *>::const_iterator ben = bi.end();
881 for (; bit != ben; ++bit)
882 cited_entries_.push_back((*bit)->key());
886 void BiblioInfo::makeCitationLabels(Buffer const & buf)
888 collectCitedEntries(buf);
889 CiteEngineType const engine_type = buf.params().citeEngineType();
890 bool const numbers = (engine_type == ENGINE_TYPE_NUMERICAL);
894 // used to remember the last one we saw
895 // we'll be comparing entries to see if we need to add
896 // modifiers, like "1984a"
897 map<docstring, BibTeXInfo>::iterator last;
899 vector<docstring>::const_iterator it = cited_entries_.begin();
900 vector<docstring>::const_iterator const en = cited_entries_.end();
901 for (; it != en; ++it) {
902 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
903 // this shouldn't happen, but...
904 if (biit == bimap_.end())
905 // ...fail gracefully, anyway.
907 BibTeXInfo & entry = biit->second;
909 docstring const num = convert<docstring>(++keynumber);
910 entry.setCiteNumber(num);
912 if (it != cited_entries_.begin()
913 && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
914 // we access the year via getYear() so as to get it from the xref,
915 // if we need to do so
916 && getYear(entry.key()) == getYear(last->second.key())) {
918 // so the last one should have been 'a'
919 last->second.setModifier('a');
921 } else if (modifier == 'z')
928 entry.setModifier(modifier);
929 // remember the last one
936 //////////////////////////////////////////////////////////////////////
940 //////////////////////////////////////////////////////////////////////
943 CitationStyle citationStyleFromString(string const & command)
949 string cmd = command;
951 cs.forceUpperCase = true;
955 size_t const n = cmd.size() - 1;
957 cs.fullAuthorList = true;
958 cmd = cmd.substr(0, n);
966 string citationStyleToString(const CitationStyle & cs)
969 if (cs.forceUpperCase)
971 if (cs.fullAuthorList)