3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
11 * Full author contact details are available in file CREDITS.
16 #include "BiblioInfo.h"
18 #include "BufferParams.h"
19 #include "buffer_funcs.h"
21 #include "InsetIterator.h"
23 #include "Paragraph.h"
24 #include "TextClass.h"
25 #include "TocBackend.h"
27 #include "support/convert.h"
28 #include "support/debug.h"
29 #include "support/docstream.h"
30 #include "support/gettext.h"
31 #include "support/lassert.h"
32 #include "support/lstrings.h"
33 #include "support/regex.h"
34 #include "support/textutils.h"
39 using namespace lyx::support;
46 // gets the "family name" from an author-type string
47 docstring familyName(docstring const & name)
52 // first we look for a comma, and take the last name to be everything
53 // preceding the right-most one, so that we also get the "jr" part.
54 docstring::size_type idx = name.rfind(',');
55 if (idx != docstring::npos)
56 return ltrim(name.substr(0, idx));
58 // OK, so now we want to look for the last name. We're going to
59 // include the "von" part. This isn't perfect.
60 // Split on spaces, to get various tokens.
61 vector<docstring> pieces = getVectorFromString(name, from_ascii(" "));
62 // If we only get two, assume the last one is the last name
63 if (pieces.size() <= 2)
66 // Now we look for the first token that begins with a lower case letter.
67 vector<docstring>::const_iterator it = pieces.begin();
68 vector<docstring>::const_iterator en = pieces.end();
69 for (; it != en; ++it) {
72 char_type const c = (*it)[0];
77 if (it == en) // we never found a "von"
80 // reconstruct what we need to return
83 for (; it != en; ++it) {
94 // converts a string containing LaTeX commands into unicode
96 docstring convertLaTeXCommands(docstring const & str)
101 bool scanning_cmd = false;
102 bool scanning_math = false;
103 bool escaped = false; // used to catch \$, etc.
104 while (!val.empty()) {
105 char_type const ch = val[0];
107 // if we're scanning math, we output everything until we
108 // find an unescaped $, at which point we break out.
115 scanning_math = false;
121 // if we're scanning a command name, then we just
122 // discard characters until we hit something that
125 if (isAlphaASCII(ch)) {
130 // so we're done with this command.
131 // now we fall through and check this character.
132 scanning_cmd = false;
135 // was the last character a \? If so, then this is something like:
136 // \\ or \$, so we'll just output it. That's probably not always right...
138 // exception: output \, as THIN SPACE
140 ret.push_back(0x2009);
151 scanning_math = true;
155 // we just ignore braces
156 if (ch == '{' || ch == '}') {
161 // we're going to check things that look like commands, so if
162 // this doesn't, just output it.
169 // ok, could be a command of some sort
170 // let's see if it corresponds to some unicode
171 // unicodesymbols has things in the form: \"{u},
172 // whereas we may see things like: \"u. So we'll
173 // look for that and change it, if necessary.
174 // FIXME: This is a sort of mini-tex2lyx.
175 // Use the real tex2lyx instead!
176 static lyx::regex const reg("^\\\\\\W\\w");
177 if (lyx::regex_search(to_utf8(val), reg)) {
178 val.insert(3, from_ascii("}"));
179 val.insert(2, from_ascii("{"));
183 docstring const cnvtd = Encodings::fromLaTeXCommand(val,
184 Encodings::TEXT_CMD, termination, rem);
185 if (!cnvtd.empty()) {
186 // it did, so we'll take that bit and proceed with what's left
191 // it's a command of some sort
202 //////////////////////////////////////////////////////////////////////
206 //////////////////////////////////////////////////////////////////////
208 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
209 : is_bibtex_(true), bib_key_(key), entry_type_(type), info_(),
214 docstring const BibTeXInfo::getAbbreviatedAuthor(bool jurabib_style, string lang) const
217 docstring const opt = label();
222 docstring const remainder = trim(split(opt, authors, '('));
223 if (remainder.empty())
224 // in this case, we didn't find a "(",
225 // so we don't have author (year)
230 docstring author = convertLaTeXCommands(operator[]("author"));
231 if (author.empty()) {
232 author = convertLaTeXCommands(operator[]("editor"));
237 // FIXME Move this to a separate routine that can
238 // be called from elsewhere.
240 // OK, we've got some names. Let's format them.
241 // Try to split the author list on " and "
242 vector<docstring> const authors =
243 getVectorFromString(author, from_ascii(" and "));
245 if (jurabib_style && (authors.size() == 2 || authors.size() == 3)) {
246 docstring shortauthor = familyName(authors[0])
247 + "/" + familyName(authors[1]);
248 if (authors.size() == 3)
249 shortauthor += "/" + familyName(authors[2]);
253 if (authors.size() == 2)
254 return bformat(translateIfPossible(from_ascii("%1$s and %2$s"), lang),
255 familyName(authors[0]), familyName(authors[1]));
257 if (authors.size() > 2)
258 return bformat(translateIfPossible(from_ascii("%1$s et al."), lang),
259 familyName(authors[0]));
261 return familyName(authors[0]);
265 docstring const BibTeXInfo::getYear() const
268 return operator[]("year");
270 docstring const opt = label();
275 docstring tmp = split(opt, authors, '(');
277 // we don't have author (year)
280 tmp = split(tmp, year, ')');
285 docstring const BibTeXInfo::getXRef() const
289 return operator[]("crossref");
295 string parseOptions(string const & format, string & optkey,
296 string & ifpart, string & elsepart);
298 // Calls parseOptions to deal with an embedded option, such as:
299 // {%number%[[, no.~%number%]]}
300 // which must appear at the start of format. ifelsepart gets the
301 // whole of the option, and we return what's left after the option.
302 // we return format if there is an error.
303 string parseEmbeddedOption(string const & format, string & ifelsepart)
305 LASSERT(format[0] == '{' && format[1] == '%', return format);
309 string const rest = parseOptions(format, optkey, ifpart, elsepart);
310 if (format == rest) { // parse error
311 LYXERR0("ERROR! Couldn't parse `" << format <<"'.");
314 LASSERT(rest.size() <= format.size(), /* */);
315 ifelsepart = format.substr(0, format.size() - rest.size());
320 // Gets a "clause" from a format string, where the clause is
321 // delimited by '[[' and ']]'. Returns what is left after the
322 // clause is removed, and returns format if there is an error.
323 string getClause(string const & format, string & clause)
328 // we'll remove characters from the front of fmt as we
330 while (!fmt.empty()) {
331 if (fmt[0] == ']' && fmt.size() > 1 && fmt[1] == ']') {
336 // check for an embedded option
337 if (fmt[0] == '{' && fmt.size() > 1 && fmt[1] == '%') {
339 string const rest = parseEmbeddedOption(fmt, part);
341 LYXERR0("ERROR! Couldn't parse embedded option in `" << format <<"'.");
346 } else { // it's just a normal character
355 // parse an options string, which must appear at the start of the
356 // format parameter. puts the parsed bits in optkey, ifpart, and
357 // elsepart and returns what's left after the option is removed.
358 // if there's an error, it returns format itself.
359 string parseOptions(string const & format, string & optkey,
360 string & ifpart, string & elsepart)
362 LASSERT(format[0] == '{' && format[1] == '%', return format);
364 string fmt = format.substr(2);
365 size_t pos = fmt.find('%'); // end of key
366 if (pos == string::npos) {
367 LYXERR0("Error parsing `" << format <<"'. Can't find end of key.");
370 optkey = fmt.substr(0,pos);
371 fmt = fmt.substr(pos + 1);
372 // [[format]] should be next
373 if (fmt[0] != '[' || fmt[1] != '[') {
374 LYXERR0("Error parsing `" << format <<"'. Can't find '[[' after key.");
379 fmt = getClause(curfmt, ifpart);
381 LYXERR0("Error parsing `" << format <<"'. Couldn't get if clause.");
385 if (fmt[0] == '}') // we're done, no else clause
386 return fmt.substr(1);
388 // else part should follow
389 if (fmt[0] != '[' || fmt[1] != '[') {
390 LYXERR0("Error parsing `" << format <<"'. Can't find else clause.");
395 fmt = getClause(curfmt, elsepart);
397 if (fmt == curfmt || fmt[0] != '}') {
398 LYXERR0("Error parsing `" << format <<"'. Can't find end of option.");
401 return fmt.substr(1);
408 docstring BibTeXInfo::expandFormat(string const & format,
409 BibTeXInfo const * const xref, int & counter, Buffer const & buf,
410 bool richtext, docstring before, docstring after, docstring dialog, bool next) const
412 // incorrect use of macros could put us in an infinite loop
413 static int max_passes = 5000;
414 docstring ret; // return value
416 string lang = buf.params().language->code();
417 bool scanning_key = false;
418 bool scanning_rich = false;
420 CiteEngineType const engine_type = buf.params().citeEngineType();
422 // we'll remove characters from the front of fmt as we
424 while (!fmt.empty()) {
425 if (counter++ > max_passes) {
426 LYXERR0("Recursion limit reached while parsing `"
431 char_type thischar = fmt[0];
432 if (thischar == '%') {
433 // beginning or end of key
436 scanning_key = false;
437 // so we replace the key with its value, which may be empty
440 // FIXME: instead of passing the buf, just past the macros
441 // FIXME: and the language code
443 buf.params().documentClass().getCiteMacro(engine_type, key);
444 fmt = val + fmt.substr(1);
446 } else if (key[0] == '_') {
447 // a translatable bit
449 buf.params().documentClass().getCiteMacro(engine_type, key);
450 docstring const trans =
451 translateIfPossible(from_utf8(val), lang);
454 docstring const val =
455 getValueForKey(key, before, after, dialog, xref, lang);
464 else if (thischar == '{') {
465 // beginning of option?
467 LYXERR0("ERROR: Found `{' when scanning key in `" << format << "'.");
470 if (fmt.size() > 1) {
472 // it is the beginning of an optional format
476 string const newfmt =
477 parseOptions(fmt, optkey, ifpart, elsepart);
478 if (newfmt == fmt) // parse error
481 docstring const val =
482 getValueForKey(optkey, before, after, dialog, xref, lang);
483 if (optkey == "next" && next)
484 ret += from_utf8(ifpart); // without expansion
485 else if (!val.empty())
486 ret += expandFormat(ifpart, xref, counter, buf,
487 richtext, before, after, dialog, next);
488 else if (!elsepart.empty())
489 ret += expandFormat(elsepart, xref, counter, buf,
490 richtext, before, after, dialog, next);
491 // fmt will have been shortened for us already
495 // beginning of rich text
496 scanning_rich = true;
501 // we are here if '{' was not followed by % or !.
502 // So it's just a character.
505 else if (scanning_rich && thischar == '!'
506 && fmt.size() > 1 && fmt[1] == '}') {
508 scanning_rich = false;
512 else if (scanning_key)
513 key += char(thischar);
518 // we need to escape '<' and '>'
521 else if (thischar == '>')
526 } else if (!scanning_rich /* && !richtext */)
528 // else the character is discarded, which will happen only if
529 // richtext == false and we are scanning rich text
533 LYXERR0("Never found end of key in `" << format << "'!");
537 LYXERR0("Never found end of rich text in `" << format << "'!");
544 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref,
545 Buffer const & buf, bool richtext) const
551 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
556 CiteEngineType const engine_type = buf.params().citeEngineType();
557 DocumentClass const & dc = buf.params().documentClass();
558 string const & format = dc.getCiteFormat(engine_type, to_utf8(entry_type_));
560 info_ = expandFormat(format, xref, counter, buf, richtext);
563 info_ = convertLaTeXCommands(info_);
568 docstring const BibTeXInfo::getLabel(BibTeXInfo const * const xref,
569 Buffer const & buf, string const & format, bool richtext,
570 docstring before, docstring after, docstring dialog, bool next) const
576 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
583 loclabel = expandFormat(format, xref, counter, buf, richtext,
584 before, after, dialog, next);
586 if (!loclabel.empty())
587 loclabel = convertLaTeXCommands(loclabel);
592 docstring const & BibTeXInfo::operator[](docstring const & field) const
594 BibTeXInfo::const_iterator it = find(field);
597 static docstring const empty_value = docstring();
602 docstring const & BibTeXInfo::operator[](string const & field) const
604 return operator[](from_ascii(field));
608 docstring BibTeXInfo::getValueForKey(string const & key,
609 docstring const & before, docstring const & after, docstring const & dialog,
610 BibTeXInfo const * const xref, string lang) const
612 docstring ret = operator[](key);
613 if (ret.empty() && xref)
618 // FIXME: dialog, textbefore and textafter have nothing to do with this
621 else if (key == "entrytype")
623 else if (key == "key")
625 else if (key == "label")
627 else if (key == "abbrvauthor")
628 // Special key to provide abbreviated author names.
629 return getAbbreviatedAuthor(false, lang);
630 else if (key == "shortauthor")
631 // When shortauthor is not defined, jurabib automatically
632 // provides jurabib-style abbreviated author names. We do
634 return getAbbreviatedAuthor(true, lang);
635 else if (key == "shorttitle") {
636 // When shorttitle is not defined, jurabib uses for `article'
637 // and `periodical' entries the form `journal volume [year]'
638 // and for other types of entries it uses the `title' field.
639 if (entry_type_ == "article" || entry_type_ == "periodical")
640 return operator[]("journal") + " " + operator[]("volume")
641 + " [" + operator[]("year") + "]";
643 return operator[]("title");
644 } else if (key == "textbefore")
646 else if (key == "textafter")
648 else if (key == "year")
654 //////////////////////////////////////////////////////////////////////
658 //////////////////////////////////////////////////////////////////////
662 // A functor for use with sort, leading to case insensitive sorting
663 class compareNoCase: public binary_function<docstring, docstring, bool>
666 bool operator()(docstring const & s1, docstring const & s2) const {
667 return compare_no_case(s1, s2) < 0;
674 vector<docstring> const BiblioInfo::getKeys() const
676 vector<docstring> bibkeys;
677 BiblioInfo::const_iterator it = begin();
678 for (; it != end(); ++it)
679 bibkeys.push_back(it->first);
680 sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
685 vector<docstring> const BiblioInfo::getFields() const
687 vector<docstring> bibfields;
688 set<docstring>::const_iterator it = field_names_.begin();
689 set<docstring>::const_iterator end = field_names_.end();
690 for (; it != end; ++it)
691 bibfields.push_back(*it);
692 sort(bibfields.begin(), bibfields.end());
697 vector<docstring> const BiblioInfo::getEntries() const
699 vector<docstring> bibentries;
700 set<docstring>::const_iterator it = entry_types_.begin();
701 set<docstring>::const_iterator end = entry_types_.end();
702 for (; it != end; ++it)
703 bibentries.push_back(*it);
704 sort(bibentries.begin(), bibentries.end());
709 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key, string lang) const
711 BiblioInfo::const_iterator it = find(key);
714 BibTeXInfo const & data = it->second;
715 return data.getAbbreviatedAuthor(false, lang);
719 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
721 BiblioInfo::const_iterator it = find(key);
724 BibTeXInfo const & data = it->second;
725 return data.citeNumber();
729 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier, string lang) const
731 BiblioInfo::const_iterator it = find(key);
734 BibTeXInfo const & data = it->second;
735 docstring year = data.getYear();
737 // let's try the crossref
738 docstring const xref = data.getXRef();
741 return translateIfPossible(from_ascii("No year"), lang);
742 BiblioInfo::const_iterator const xrefit = find(xref);
745 return translateIfPossible(from_ascii("No year"), lang);
746 BibTeXInfo const & xref_data = xrefit->second;
747 year = xref_data.getYear();
749 if (use_modifier && data.modifier() != 0)
750 year += data.modifier();
755 docstring const BiblioInfo::getInfo(docstring const & key,
756 Buffer const & buf, bool richtext) const
758 BiblioInfo::const_iterator it = find(key);
760 return docstring(_("Bibliography entry not found!"));
761 BibTeXInfo const & data = it->second;
762 BibTeXInfo const * xrefptr = 0;
763 docstring const xref = data.getXRef();
765 BiblioInfo::const_iterator const xrefit = find(xref);
767 xrefptr = &(xrefit->second);
769 return data.getInfo(xrefptr, buf, richtext);
773 docstring const BiblioInfo::getLabel(vector<docstring> const & keys,
774 Buffer const & buf, string const & style, bool richtext,
775 docstring const & before, docstring const & after, docstring const & dialog) const
777 CiteEngineType const engine_type = buf.params().citeEngineType();
778 DocumentClass const & dc = buf.params().documentClass();
779 string const & format = dc.getCiteFormat(engine_type, style, "cite");
780 docstring ret = from_utf8(format);
781 vector<docstring>::const_iterator key = keys.begin();
782 vector<docstring>::const_iterator ken = keys.end();
783 for (; key != ken; ++key) {
784 BiblioInfo::const_iterator it = find(*key);
785 BibTeXInfo empty_data;
786 empty_data.key(*key);
787 BibTeXInfo & data = empty_data;
788 BibTeXInfo const * xrefptr = 0;
791 docstring const xref = data.getXRef();
793 BiblioInfo::const_iterator const xrefit = find(xref);
795 xrefptr = &(xrefit->second);
798 ret = data.getLabel(xrefptr, buf, to_utf8(ret), richtext,
799 before, after, dialog, key+1 != ken);
805 bool BiblioInfo::isBibtex(docstring const & key) const
807 BiblioInfo::const_iterator it = find(key);
810 return it->second.isBibTeX();
814 vector<docstring> const BiblioInfo::getCiteStrings(
815 vector<docstring> const & keys, vector<CitationStyle> const & styles,
816 Buffer const & buf, bool richtext, docstring const & before,
817 docstring const & after, docstring const & dialog) const
820 return vector<docstring>();
823 vector<docstring> vec(styles.size());
824 for (size_t i = 0; i != vec.size(); ++i) {
825 style = styles[i].cmd;
826 vec[i] = getLabel(keys, buf, style, richtext, before, after, dialog);
833 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
835 bimap_.insert(info.begin(), info.end());
836 field_names_.insert(info.field_names_.begin(), info.field_names_.end());
837 entry_types_.insert(info.entry_types_.begin(), info.entry_types_.end());
843 // used in xhtml to sort a list of BibTeXInfo objects
844 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
846 docstring const lauth = lhs->getAbbreviatedAuthor();
847 docstring const rauth = rhs->getAbbreviatedAuthor();
848 docstring const lyear = lhs->getYear();
849 docstring const ryear = rhs->getYear();
850 docstring const ltitl = lhs->operator[]("title");
851 docstring const rtitl = rhs->operator[]("title");
852 return (lauth < rauth)
853 || (lauth == rauth && lyear < ryear)
854 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
860 void BiblioInfo::collectCitedEntries(Buffer const & buf)
862 cited_entries_.clear();
863 // We are going to collect all the citation keys used in the document,
864 // getting them from the TOC.
865 // FIXME We may want to collect these differently, in the first case,
866 // so that we might have them in order of appearance.
867 set<docstring> citekeys;
868 Toc const & toc = buf.tocBackend().toc("citation");
869 Toc::const_iterator it = toc.begin();
870 Toc::const_iterator const en = toc.end();
871 for (; it != en; ++it) {
872 if (it->str().empty())
874 vector<docstring> const keys = getVectorFromString(it->str());
875 citekeys.insert(keys.begin(), keys.end());
877 if (citekeys.empty())
880 // We have a set of the keys used in this document.
881 // We will now convert it to a list of the BibTeXInfo objects used in
883 vector<BibTeXInfo const *> bi;
884 set<docstring>::const_iterator cit = citekeys.begin();
885 set<docstring>::const_iterator const cen = citekeys.end();
886 for (; cit != cen; ++cit) {
887 BiblioInfo::const_iterator const bt = find(*cit);
888 if (bt == end() || !bt->second.isBibTeX())
890 bi.push_back(&(bt->second));
893 sort(bi.begin(), bi.end(), lSorter);
895 // Now we can write the sorted keys
896 vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
897 vector<BibTeXInfo const *>::const_iterator ben = bi.end();
898 for (; bit != ben; ++bit)
899 cited_entries_.push_back((*bit)->key());
903 void BiblioInfo::makeCitationLabels(Buffer const & buf)
905 collectCitedEntries(buf);
906 CiteEngineType const engine_type = buf.params().citeEngineType();
907 bool const numbers = (engine_type == ENGINE_TYPE_NUMERICAL);
911 // used to remember the last one we saw
912 // we'll be comparing entries to see if we need to add
913 // modifiers, like "1984a"
914 map<docstring, BibTeXInfo>::iterator last;
916 vector<docstring>::const_iterator it = cited_entries_.begin();
917 vector<docstring>::const_iterator const en = cited_entries_.end();
918 for (; it != en; ++it) {
919 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
920 // this shouldn't happen, but...
921 if (biit == bimap_.end())
922 // ...fail gracefully, anyway.
924 BibTeXInfo & entry = biit->second;
926 docstring const num = convert<docstring>(++keynumber);
927 entry.setCiteNumber(num);
929 if (it != cited_entries_.begin()
930 && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
931 // we access the year via getYear() so as to get it from the xref,
932 // if we need to do so
933 && getYear(entry.key()) == getYear(last->second.key())) {
935 // so the last one should have been 'a'
936 last->second.setModifier('a');
938 } else if (modifier == 'z')
945 entry.setModifier(modifier);
946 // remember the last one
953 //////////////////////////////////////////////////////////////////////
957 //////////////////////////////////////////////////////////////////////
960 CitationStyle citationStyleFromString(string const & command)
966 string cmd = command;
968 cs.forceUpperCase = true;
972 size_t const n = cmd.size() - 1;
974 cs.fullAuthorList = true;
975 cmd = cmd.substr(0, n);
983 string citationStyleToString(const CitationStyle & cs)
986 if (cs.forceUpperCase)
988 if (cs.fullAuthorList)