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 // FIXME: This is a sort of mini-tex2lyx.
173 // Use the real tex2lyx instead!
174 static lyx::regex const reg("^\\\\\\W\\w");
175 if (lyx::regex_search(to_utf8(val), reg)) {
176 val.insert(3, from_ascii("}"));
177 val.insert(2, from_ascii("{"));
181 docstring const cnvtd = Encodings::fromLaTeXCommand(val,
182 Encodings::TEXT_CMD, termination, rem);
183 if (!cnvtd.empty()) {
184 // it did, so we'll take that bit and proceed with what's left
189 // it's a command of some sort
200 //////////////////////////////////////////////////////////////////////
204 //////////////////////////////////////////////////////////////////////
206 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
207 : is_bibtex_(true), bib_key_(key), entry_type_(type), info_(),
212 docstring const BibTeXInfo::getAbbreviatedAuthor(bool jurabib_style) const
215 docstring const opt = label();
220 docstring const remainder = trim(split(opt, authors, '('));
221 if (remainder.empty())
222 // in this case, we didn't find a "(",
223 // so we don't have author (year)
228 docstring author = convertLaTeXCommands(operator[]("author"));
229 if (author.empty()) {
230 author = convertLaTeXCommands(operator[]("editor"));
235 // FIXME Move this to a separate routine that can
236 // be called from elsewhere.
238 // OK, we've got some names. Let's format them.
239 // Try to split the author list on " and "
240 vector<docstring> const authors =
241 getVectorFromString(author, from_ascii(" and "));
243 if (jurabib_style && (authors.size() == 2 || authors.size() == 3)) {
244 docstring shortauthor = familyName(authors[0])
245 + "/" + familyName(authors[1]);
246 if (authors.size() == 3)
247 shortauthor += "/" + familyName(authors[2]);
251 if (authors.size() == 2)
252 return bformat(_("%1$s and %2$s"),
253 familyName(authors[0]), familyName(authors[1]));
255 if (authors.size() > 2)
256 return bformat(_("%1$s et al."), familyName(authors[0]));
258 return familyName(authors[0]);
262 docstring const BibTeXInfo::getYear() const
265 return operator[]("year");
267 docstring const opt = label();
272 docstring tmp = split(opt, authors, '(');
274 // we don't have author (year)
277 tmp = split(tmp, year, ')');
282 docstring const BibTeXInfo::getXRef() const
286 return operator[]("crossref");
291 string parseOptions(string const & format, string & optkey,
292 string & ifpart, string & elsepart);
294 // Calls parseOptions to deal with an embedded option, such as:
295 // {%number%[[, no.~%number%]]}
296 // which must appear at the start of format. ifelsepart gets the
297 // whole of the option, and we return what's left after the option.
298 // we return format if there is an error.
299 string parseEmbeddedOption(string const & format, string & ifelsepart)
301 LASSERT(format[0] == '{' && format[1] == '%', return format);
305 string const rest = parseOptions(format, optkey, ifpart, elsepart);
306 if (format == rest) { // parse error
307 LYXERR0("ERROR! Couldn't parse `" << format <<"'.");
310 LASSERT(rest.size() <= format.size(), /* */);
311 ifelsepart = format.substr(0, format.size() - rest.size());
316 // Gets a "clause" from a format string, where the clause is
317 // delimited by '[[' and ']]'. Returns what is left after the
318 // clause is removed, and returns format if there is an error.
319 string getClause(string const & format, string & clause)
324 // we'll remove characters from the front of fmt as we
327 if (fmt[0] == ']' && fmt.size() > 1 && fmt[1] == ']') {
332 // check for an embedded option
333 if (fmt[0] == '{' && fmt.size() > 1 && fmt[1] == '%') {
335 string const rest = parseEmbeddedOption(fmt, part);
337 LYXERR0("ERROR! Couldn't parse embedded option in `" << format <<"'.");
342 } else { // it's just a normal character
351 // parse an options string, which must appear at the start of the
352 // format parameter. puts the parsed bits in optkey, ifpart, and
353 // elsepart and returns what's left after the option is removed.
354 // if there's an error, it returns format itself.
355 string parseOptions(string const & format, string & optkey,
356 string & ifpart, string & elsepart)
358 LASSERT(format[0] == '{' && format[1] == '%', return format);
360 string fmt = format.substr(2);
361 size_t pos = fmt.find('%'); // end of key
362 if (pos == string::npos) {
363 LYXERR0("Error parsing `" << format <<"'. Can't find end of key.");
366 optkey = fmt.substr(0,pos);
367 fmt = fmt.substr(pos + 1);
368 // [[format]] should be next
369 if (fmt[0] != '[' || fmt[1] != '[') {
370 LYXERR0("Error parsing `" << format <<"'. Can't find '[[' after key.");
375 fmt = getClause(curfmt, ifpart);
377 LYXERR0("Error parsing `" << format <<"'. Couldn't get if clause.");
381 if (fmt[0] == '}') // we're done, no else clause
382 return fmt.substr(1);
384 // else part should follow
385 if (fmt[0] != '[' || fmt[1] != '[') {
386 LYXERR0("Error parsing `" << format <<"'. Can't find else clause.");
391 fmt = getClause(curfmt, elsepart);
393 if (fmt == curfmt || fmt[0] != '}') {
394 LYXERR0("Error parsing `" << format <<"'. Can't find end of option.");
397 return fmt.substr(1);
403 docstring BibTeXInfo::expandFormat(string const & format,
404 BibTeXInfo const * const xref, int & counter, Buffer const & buf,
405 bool richtext, docstring before, docstring after, docstring dialog, bool next) const
407 // incorrect use of macros could put us in an infinite loop
408 static int max_passes = 5000;
409 docstring ret; // return value
411 bool scanning_key = false;
412 bool scanning_rich = false;
414 CiteEngineType const engine_type = buf.params().citeEngineType();
416 // we'll remove characters from the front of fmt as we
419 if (counter++ > max_passes) {
420 LYXERR0("Recursion limit reached while parsing `"
425 char_type thischar = fmt[0];
426 if (thischar == '%') {
427 // beginning or end of key
430 scanning_key = false;
431 // so we replace the key with its value, which may be empty
434 // FIXME: instead of passing the buf, just past the macros
435 // FIXME: and the language code
437 buf.params().documentClass().getCiteMacro(engine_type, key);
438 fmt = val + fmt.substr(1);
440 } else if (key[0] == '_') {
441 // a translatable bit
443 buf.params().documentClass().getCiteMacro(engine_type, key);
444 docstring const trans =
445 translateIfPossible(from_utf8(val), buf.params().language->code());
448 docstring const val = getValueForKey(key, before, after, dialog, xref);
457 else if (thischar == '{') {
458 // beginning of option?
460 LYXERR0("ERROR: Found `{' when scanning key in `" << format << "'.");
463 if (fmt.size() > 1) {
465 // it is the beginning of an optional format
469 string const newfmt =
470 parseOptions(fmt, optkey, ifpart, elsepart);
471 if (newfmt == fmt) // parse error
474 docstring const val = getValueForKey(optkey, before, after, dialog, xref);
475 if (optkey == "next" && next)
476 ret += from_utf8(ifpart); // without expansion
477 else if (!val.empty())
478 ret += expandFormat(ifpart, xref, counter, buf,
479 richtext, before, after, dialog, next);
480 else if (!elsepart.empty())
481 ret += expandFormat(elsepart, xref, counter, buf,
482 richtext, before, after, dialog, next);
483 // fmt will have been shortened for us already
487 // beginning of rich text
488 scanning_rich = true;
493 // we are here if '{' was not followed by % or !.
494 // So it's just a character.
497 else if (scanning_rich && thischar == '!'
498 && fmt.size() > 1 && fmt[1] == '}') {
500 scanning_rich = false;
504 else if (scanning_key)
505 key += char(thischar);
510 // we need to escape '<' and '>'
513 else if (thischar == '>')
518 } else if (!scanning_rich /* && !richtext */)
520 // else the character is discarded, which will happen only if
521 // richtext == false and we are scanning rich text
525 LYXERR0("Never found end of key in `" << format << "'!");
529 LYXERR0("Never found end of rich text in `" << format << "'!");
536 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref,
537 Buffer const & buf, bool richtext) const
543 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
548 CiteEngineType const engine_type = buf.params().citeEngineType();
549 DocumentClass const & dc = buf.params().documentClass();
550 string const & format = dc.getCiteFormat(engine_type, to_utf8(entry_type_));
552 info_ = expandFormat(format, xref, counter, buf, richtext);
555 info_ = convertLaTeXCommands(info_);
560 docstring const BibTeXInfo::getLabel(BibTeXInfo const * const xref,
561 Buffer const & buf, string const & format, bool richtext,
562 docstring before, docstring after, docstring dialog, bool next) const
568 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
575 loclabel = expandFormat(format, xref, counter, buf, richtext,
576 before, after, dialog, next);
578 if (!loclabel.empty())
579 loclabel = convertLaTeXCommands(loclabel);
584 docstring const & BibTeXInfo::operator[](docstring const & field) const
586 BibTeXInfo::const_iterator it = find(field);
589 static docstring const empty_value = docstring();
594 docstring const & BibTeXInfo::operator[](string const & field) const
596 return operator[](from_ascii(field));
600 docstring BibTeXInfo::getValueForKey(string const & key,
601 docstring const & before, docstring const & after, docstring const & dialog,
602 BibTeXInfo const * const xref) const
604 docstring ret = operator[](key);
605 if (ret.empty() && xref)
610 // FIXME: dialog, textbefore and textafter have nothing to do with this
613 else if (key == "entrytype")
615 else if (key == "key")
617 else if (key == "label")
619 else if (key == "abbrvauthor")
620 // Special key to provide abbreviated author names.
621 return getAbbreviatedAuthor();
622 else if (key == "shortauthor")
623 // When shortauthor is not defined, jurabib automatically
624 // provides jurabib-style abbreviated author names. We do
626 return getAbbreviatedAuthor(true);
627 else if (key == "shorttitle") {
628 // When shorttitle is not defined, jurabib uses for `article'
629 // and `periodical' entries the form `journal volume [year]'
630 // and for other types of entries it uses the `title' field.
631 if (entry_type_ == "article" || entry_type_ == "periodical")
632 return operator[]("journal") + " " + operator[]("volume")
633 + " [" + operator[]("year") + "]";
635 return operator[]("title");
636 } else if (key == "textbefore")
638 else if (key == "textafter")
640 else if (key == "year")
646 //////////////////////////////////////////////////////////////////////
650 //////////////////////////////////////////////////////////////////////
653 // A functor for use with sort, leading to case insensitive sorting
654 class compareNoCase: public binary_function<docstring, docstring, bool>
657 bool operator()(docstring const & s1, docstring const & s2) const {
658 return compare_no_case(s1, s2) < 0;
664 vector<docstring> const BiblioInfo::getKeys() const
666 vector<docstring> bibkeys;
667 BiblioInfo::const_iterator it = begin();
668 for (; it != end(); ++it)
669 bibkeys.push_back(it->first);
670 sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
675 vector<docstring> const BiblioInfo::getFields() const
677 vector<docstring> bibfields;
678 set<docstring>::const_iterator it = field_names_.begin();
679 set<docstring>::const_iterator end = field_names_.end();
680 for (; it != end; ++it)
681 bibfields.push_back(*it);
682 sort(bibfields.begin(), bibfields.end());
687 vector<docstring> const BiblioInfo::getEntries() const
689 vector<docstring> bibentries;
690 set<docstring>::const_iterator it = entry_types_.begin();
691 set<docstring>::const_iterator end = entry_types_.end();
692 for (; it != end; ++it)
693 bibentries.push_back(*it);
694 sort(bibentries.begin(), bibentries.end());
699 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
701 BiblioInfo::const_iterator it = find(key);
704 BibTeXInfo const & data = it->second;
705 return data.getAbbreviatedAuthor();
709 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
711 BiblioInfo::const_iterator it = find(key);
714 BibTeXInfo const & data = it->second;
715 return data.citeNumber();
719 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier) const
721 BiblioInfo::const_iterator it = find(key);
724 BibTeXInfo const & data = it->second;
725 docstring year = data.getYear();
727 // let's try the crossref
728 docstring const xref = data.getXRef();
730 return _("No year"); // no luck
731 BiblioInfo::const_iterator const xrefit = find(xref);
733 return _("No year"); // no luck again
734 BibTeXInfo const & xref_data = xrefit->second;
735 year = xref_data.getYear();
737 if (use_modifier && data.modifier() != 0)
738 year += data.modifier();
743 docstring const BiblioInfo::getInfo(docstring const & key,
744 Buffer const & buf, bool richtext) const
746 BiblioInfo::const_iterator it = find(key);
748 return docstring(_("Bibliography entry not found!"));
749 BibTeXInfo const & data = it->second;
750 BibTeXInfo const * xrefptr = 0;
751 docstring const xref = data.getXRef();
753 BiblioInfo::const_iterator const xrefit = find(xref);
755 xrefptr = &(xrefit->second);
757 return data.getInfo(xrefptr, buf, richtext);
761 docstring const BiblioInfo::getLabel(vector<docstring> const & keys,
762 Buffer const & buf, string const & style, bool richtext,
763 docstring const & before, docstring const & after, docstring const & dialog) const
765 CiteEngineType const engine_type = buf.params().citeEngineType();
766 DocumentClass const & dc = buf.params().documentClass();
767 string const & format = dc.getCiteFormat(engine_type, style, "cite");
768 docstring ret = from_utf8(format);
769 vector<docstring>::const_iterator key = keys.begin();
770 vector<docstring>::const_iterator ken = keys.end();
771 for (; key != ken; ++key) {
772 BiblioInfo::const_iterator it = find(*key);
773 BibTeXInfo empty_data;
774 empty_data.key(*key);
775 BibTeXInfo & data = empty_data;
776 BibTeXInfo const * xrefptr = 0;
779 docstring const xref = data.getXRef();
781 BiblioInfo::const_iterator const xrefit = find(xref);
783 xrefptr = &(xrefit->second);
786 ret = data.getLabel(xrefptr, buf, to_utf8(ret), richtext,
787 before, after, dialog, key+1 != ken);
793 bool BiblioInfo::isBibtex(docstring const & key) const
795 BiblioInfo::const_iterator it = find(key);
798 return it->second.isBibTeX();
802 vector<docstring> const BiblioInfo::getCiteStrings(
803 vector<docstring> const & keys, vector<CitationStyle> const & styles,
804 Buffer const & buf, bool richtext, docstring const & before,
805 docstring const & after, docstring const & dialog) const
808 return vector<docstring>();
811 vector<docstring> vec(styles.size());
812 for (size_t i = 0; i != vec.size(); ++i) {
813 style = styles[i].cmd;
814 vec[i] = getLabel(keys, buf, style, richtext, before, after, dialog);
821 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
823 bimap_.insert(info.begin(), info.end());
824 field_names_.insert(info.field_names_.begin(), info.field_names_.end());
825 entry_types_.insert(info.entry_types_.begin(), info.entry_types_.end());
830 // used in xhtml to sort a list of BibTeXInfo objects
831 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
833 docstring const lauth = lhs->getAbbreviatedAuthor();
834 docstring const rauth = rhs->getAbbreviatedAuthor();
835 docstring const lyear = lhs->getYear();
836 docstring const ryear = rhs->getYear();
837 docstring const ltitl = lhs->operator[]("title");
838 docstring const rtitl = rhs->operator[]("title");
839 return (lauth < rauth)
840 || (lauth == rauth && lyear < ryear)
841 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
846 void BiblioInfo::collectCitedEntries(Buffer const & buf)
848 cited_entries_.clear();
849 // We are going to collect all the citation keys used in the document,
850 // getting them from the TOC.
851 // FIXME We may want to collect these differently, in the first case,
852 // so that we might have them in order of appearance.
853 set<docstring> citekeys;
854 Toc const & toc = buf.tocBackend().toc("citation");
855 Toc::const_iterator it = toc.begin();
856 Toc::const_iterator const en = toc.end();
857 for (; it != en; ++it) {
858 if (it->str().empty())
860 vector<docstring> const keys = getVectorFromString(it->str());
861 citekeys.insert(keys.begin(), keys.end());
863 if (citekeys.empty())
866 // We have a set of the keys used in this document.
867 // We will now convert it to a list of the BibTeXInfo objects used in
869 vector<BibTeXInfo const *> bi;
870 set<docstring>::const_iterator cit = citekeys.begin();
871 set<docstring>::const_iterator const cen = citekeys.end();
872 for (; cit != cen; ++cit) {
873 BiblioInfo::const_iterator const bt = find(*cit);
874 if (bt == end() || !bt->second.isBibTeX())
876 bi.push_back(&(bt->second));
879 sort(bi.begin(), bi.end(), lSorter);
881 // Now we can write the sorted keys
882 vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
883 vector<BibTeXInfo const *>::const_iterator ben = bi.end();
884 for (; bit != ben; ++bit)
885 cited_entries_.push_back((*bit)->key());
889 void BiblioInfo::makeCitationLabels(Buffer const & buf)
891 collectCitedEntries(buf);
892 CiteEngineType const engine_type = buf.params().citeEngineType();
893 bool const numbers = (engine_type == ENGINE_TYPE_NUMERICAL);
897 // used to remember the last one we saw
898 // we'll be comparing entries to see if we need to add
899 // modifiers, like "1984a"
900 map<docstring, BibTeXInfo>::iterator last;
902 vector<docstring>::const_iterator it = cited_entries_.begin();
903 vector<docstring>::const_iterator const en = cited_entries_.end();
904 for (; it != en; ++it) {
905 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
906 // this shouldn't happen, but...
907 if (biit == bimap_.end())
908 // ...fail gracefully, anyway.
910 BibTeXInfo & entry = biit->second;
912 docstring const num = convert<docstring>(++keynumber);
913 entry.setCiteNumber(num);
915 if (it != cited_entries_.begin()
916 && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
917 // we access the year via getYear() so as to get it from the xref,
918 // if we need to do so
919 && getYear(entry.key()) == getYear(last->second.key())) {
921 // so the last one should have been 'a'
922 last->second.setModifier('a');
924 } else if (modifier == 'z')
931 entry.setModifier(modifier);
932 // remember the last one
939 //////////////////////////////////////////////////////////////////////
943 //////////////////////////////////////////////////////////////////////
946 CitationStyle citationStyleFromString(string const & command)
952 string cmd = command;
954 cs.forceUpperCase = true;
958 size_t const n = cmd.size() - 1;
960 cs.fullAuthorList = true;
961 cmd = cmd.substr(0, n);
969 string citationStyleToString(const CitationStyle & cs)
972 if (cs.forceUpperCase)
974 if (cs.fullAuthorList)