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 "insets/Inset.h"
27 #include "insets/InsetBibitem.h"
28 #include "insets/InsetBibtex.h"
29 #include "insets/InsetInclude.h"
31 #include "support/convert.h"
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/gettext.h"
35 #include "support/lassert.h"
36 #include "support/lstrings.h"
37 #include "support/textutils.h"
39 #include "support/regex.h"
44 using namespace lyx::support;
51 // gets the "family name" from an author-type string
52 docstring familyName(docstring const & name)
57 // first we look for a comma, and take the last name to be everything
58 // preceding the right-most one, so that we also get the "jr" part.
59 docstring::size_type idx = name.rfind(',');
60 if (idx != docstring::npos)
61 return ltrim(name.substr(0, idx));
63 // OK, so now we want to look for the last name. We're going to
64 // include the "von" part. This isn't perfect.
65 // Split on spaces, to get various tokens.
66 vector<docstring> pieces = getVectorFromString(name, from_ascii(" "));
67 // If we only get two, assume the last one is the last name
68 if (pieces.size() <= 2)
71 // Now we look for the first token that begins with a lower case letter.
72 vector<docstring>::const_iterator it = pieces.begin();
73 vector<docstring>::const_iterator en = pieces.end();
74 for (; it != en; ++it) {
75 if ((*it).size() == 0)
77 char_type const c = (*it)[0];
82 if (it == en) // we never found a "von"
85 // reconstruct what we need to return
88 for (; it != en; ++it) {
98 // converts a string containing LaTeX commands into unicode
100 docstring convertLaTeXCommands(docstring const & str)
105 bool scanning_cmd = false;
106 bool scanning_math = false;
107 bool escaped = false; // used to catch \$, etc.
109 char_type const ch = val[0];
111 // if we're scanning math, we output everything until we
112 // find an unescaped $, at which point we break out.
119 scanning_math = false;
125 // if we're scanning a command name, then we just
126 // discard characters until we hit something that
129 if (isAlphaASCII(ch)) {
134 // so we're done with this command.
135 // now we fall through and check this character.
136 scanning_cmd = false;
139 // was the last character a \? If so, then this is something like:
140 // \\ or \$, so we'll just output it. That's probably not always right...
142 // exception: output \, as THIN SPACE
144 ret.push_back(0x2009);
155 scanning_math = true;
159 // we just ignore braces
160 if (ch == '{' || ch == '}') {
165 // we're going to check things that look like commands, so if
166 // this doesn't, just output it.
173 // ok, could be a command of some sort
174 // let's see if it corresponds to some unicode
175 // unicodesymbols has things in the form: \"{u},
176 // whereas we may see things like: \"u. So we'll
177 // look for that and change it, if necessary.
178 static lyx::regex const reg("^\\\\\\W\\w");
179 if (lyx::regex_search(to_utf8(val), reg)) {
180 val.insert(3, from_ascii("}"));
181 val.insert(2, from_ascii("{"));
184 docstring const cnvtd = Encodings::fromLaTeXCommand(val, rem,
185 Encodings::TEXT_CMD);
186 if (!cnvtd.empty()) {
187 // it did, so we'll take that bit and proceed with what's left
192 // it's a command of some sort
203 //////////////////////////////////////////////////////////////////////
207 //////////////////////////////////////////////////////////////////////
209 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
210 : is_bibtex_(true), bib_key_(key), entry_type_(type), info_(),
215 docstring const BibTeXInfo::getAbbreviatedAuthor() const
218 docstring const opt = label();
223 docstring const remainder = trim(split(opt, authors, '('));
224 if (remainder.empty())
225 // in this case, we didn't find a "(",
226 // so we don't have author (year)
231 docstring author = convertLaTeXCommands(operator[]("author"));
232 if (author.empty()) {
233 author = convertLaTeXCommands(operator[]("editor"));
238 // FIXME Move this to a separate routine that can
239 // be called from elsewhere.
241 // OK, we've got some names. Let's format them.
242 // Try to split the author list on " and "
243 vector<docstring> const authors =
244 getVectorFromString(author, from_ascii(" and "));
246 if (authors.size() == 2)
247 return bformat(_("%1$s and %2$s"),
248 familyName(authors[0]), familyName(authors[1]));
250 if (authors.size() > 2)
251 return bformat(_("%1$s et al."), familyName(authors[0]));
253 return familyName(authors[0]);
257 docstring const BibTeXInfo::getYear() const
260 return operator[]("year");
262 docstring const opt = label();
267 docstring tmp = split(opt, authors, '(');
269 // we don't have author (year)
272 tmp = split(tmp, year, ')');
277 docstring const BibTeXInfo::getXRef() const
281 return operator[]("crossref");
286 string parseOptions(string const & format, string & optkey,
287 string & ifpart, string & elsepart);
289 // Calls parseOptions to deal with an embedded option, such as:
290 // {%number%[[, no.~%number%]]}
291 // which must appear at the start of format. ifelsepart gets the
292 // whole of the option, and we return what's left after the option.
293 // we return format if there is an error.
294 string parseEmbeddedOption(string const & format, string & ifelsepart)
296 LASSERT(format[0] == '{' && format[1] == '%', return format);
300 string const rest = parseOptions(format, optkey, ifpart, elsepart);
301 if (format == rest) { // parse error
302 LYXERR0("ERROR! Couldn't parse `" << format <<"'.");
305 LASSERT(rest.size() <= format.size(), /* */);
306 ifelsepart = format.substr(0, format.size() - rest.size());
311 // Gets a "clause" from a format string, where the clause is
312 // delimited by '[[' and ']]'. Returns what is left after the
313 // clause is removed, and returns format if there is an error.
314 string getClause(string const & format, string & clause)
319 // we'll remove characters from the front of fmt as we
322 if (fmt[0] == ']' && fmt.size() > 1 && fmt[1] == ']') {
327 // check for an embedded option
328 if (fmt[0] == '{' && fmt.size() > 1 && fmt[1] == '%') {
330 string const rest = parseEmbeddedOption(fmt, part);
332 LYXERR0("ERROR! Couldn't parse embedded option in `" << format <<"'.");
337 } else { // it's just a normal character
346 // parse an options string, which must appear at the start of the
347 // format parameter. puts the parsed bits in optkey, ifpart, and
348 // elsepart and returns what's left after the option is removed.
349 // if there's an error, it returns format itself.
350 string parseOptions(string const & format, string & optkey,
351 string & ifpart, string & elsepart)
353 LASSERT(format[0] == '{' && format[1] == '%', return format);
355 string fmt = format.substr(2);
356 size_t pos = fmt.find('%'); // end of key
357 if (pos == string::npos) {
358 LYXERR0("Error parsing `" << format <<"'. Can't find end of key.");
361 optkey = fmt.substr(0,pos);
362 fmt = fmt.substr(pos + 1);
363 // [[format]] should be next
364 if (fmt[0] != '[' || fmt[1] != '[') {
365 LYXERR0("Error parsing `" << format <<"'. Can't find '[[' after key.");
370 fmt = getClause(curfmt, ifpart);
372 LYXERR0("Error parsing `" << format <<"'. Couldn't get if clause.");
376 if (fmt[0] == '}') // we're done, no else clause
377 return fmt.substr(1);
379 // else part should follow
380 if (fmt[0] != '[' || fmt[1] != '[') {
381 LYXERR0("Error parsing `" << format <<"'. Can't find else clause.");
386 fmt = getClause(curfmt, elsepart);
388 if (fmt == curfmt || fmt[0] != '}') {
389 LYXERR0("Error parsing `" << format <<"'. Can't find end of option.");
392 return fmt.substr(1);
398 docstring BibTeXInfo::expandFormat(string const & format,
399 BibTeXInfo const * const xref, int & counter, Buffer const & buf,
402 // incorrect use of macros could put us in an infinite loop
403 static int max_passes = 5000;
404 docstring ret; // return value
406 bool scanning_key = false;
407 bool scanning_rich = false;
410 // we'll remove characters from the front of fmt as we
413 if (counter++ > max_passes) {
414 LYXERR0("Recursion limit reached while parsing `"
419 char_type thischar = fmt[0];
420 if (thischar == '%') {
421 // beginning or end of key
424 scanning_key = false;
425 // so we replace the key with its value, which may be empty
429 buf.params().documentClass().getCiteMacro(key);
430 fmt = val + fmt.substr(1);
432 } else if (key[0] == '_') {
433 // a translatable bit
435 buf.params().documentClass().getCiteMacro(key);
436 docstring const trans =
437 translateIfPossible(from_utf8(val), buf.params().language->code());
440 docstring const val = getValueForKey(key, xref);
449 else if (thischar == '{') {
450 // beginning of option?
452 LYXERR0("ERROR: Found `{' when scanning key in `" << format << "'.");
455 if (fmt.size() > 1) {
457 // it is the beginning of an optional format
461 string const newfmt =
462 parseOptions(fmt, optkey, ifpart, elsepart);
463 if (newfmt == fmt) // parse error
466 docstring const val = getValueForKey(optkey, xref);
468 ret += expandFormat(ifpart, xref, counter, buf, richtext);
469 else if (!elsepart.empty())
470 ret += expandFormat(elsepart, xref, counter, buf, richtext);
471 // fmt will have been shortened for us already
475 // beginning of rich text
476 scanning_rich = true;
481 // we are here if '{' was not followed by % or !.
482 // So it's just a character.
485 else if (scanning_rich && thischar == '!'
486 && fmt.size() > 1 && fmt[1] == '}') {
488 scanning_rich = false;
492 else if (scanning_key)
493 key += char(thischar);
498 // we need to escape '<' and '>'
501 else if (thischar == '>')
506 } else if (!scanning_rich /* && !richtext */)
508 // else the character is discarded, which will happen only if
509 // richtext == false and we are scanning rich text
513 LYXERR0("Never found end of key in `" << format << "'!");
517 LYXERR0("Never found end of rich text in `" << format << "'!");
524 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref,
525 Buffer const & buf, bool richtext) const
531 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
536 DocumentClass const & dc = buf.params().documentClass();
537 string const & format = dc.getCiteFormat(to_utf8(entry_type_));
539 info_ = expandFormat(format, xref, counter, buf, richtext);
542 info_ = convertLaTeXCommands(info_);
547 docstring const & BibTeXInfo::operator[](docstring const & field) const
549 BibTeXInfo::const_iterator it = find(field);
552 static docstring const empty_value = docstring();
557 docstring const & BibTeXInfo::operator[](string const & field) const
559 return operator[](from_ascii(field));
563 docstring BibTeXInfo::getValueForKey(string const & key,
564 BibTeXInfo const * const xref) const
566 docstring const ret = operator[](key);
567 if (!ret.empty() || !xref)
573 //////////////////////////////////////////////////////////////////////
577 //////////////////////////////////////////////////////////////////////
580 // A functor for use with sort, leading to case insensitive sorting
581 class compareNoCase: public binary_function<docstring, docstring, bool>
584 bool operator()(docstring const & s1, docstring const & s2) const {
585 return compare_no_case(s1, s2) < 0;
591 vector<docstring> const BiblioInfo::getKeys() const
593 vector<docstring> bibkeys;
594 BiblioInfo::const_iterator it = begin();
595 for (; it != end(); ++it)
596 bibkeys.push_back(it->first);
597 sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
602 vector<docstring> const BiblioInfo::getFields() const
604 vector<docstring> bibfields;
605 set<docstring>::const_iterator it = field_names_.begin();
606 set<docstring>::const_iterator end = field_names_.end();
607 for (; it != end; ++it)
608 bibfields.push_back(*it);
609 sort(bibfields.begin(), bibfields.end());
614 vector<docstring> const BiblioInfo::getEntries() const
616 vector<docstring> bibentries;
617 set<docstring>::const_iterator it = entry_types_.begin();
618 set<docstring>::const_iterator end = entry_types_.end();
619 for (; it != end; ++it)
620 bibentries.push_back(*it);
621 sort(bibentries.begin(), bibentries.end());
626 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
628 BiblioInfo::const_iterator it = find(key);
631 BibTeXInfo const & data = it->second;
632 return data.getAbbreviatedAuthor();
636 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
638 BiblioInfo::const_iterator it = find(key);
641 BibTeXInfo const & data = it->second;
642 return data.citeNumber();
646 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier) const
648 BiblioInfo::const_iterator it = find(key);
651 BibTeXInfo const & data = it->second;
652 docstring year = data.getYear();
654 // let's try the crossref
655 docstring const xref = data.getXRef();
657 return _("No year"); // no luck
658 BiblioInfo::const_iterator const xrefit = find(xref);
660 return _("No year"); // no luck again
661 BibTeXInfo const & xref_data = xrefit->second;
662 year = xref_data.getYear();
664 if (use_modifier && data.modifier() != 0)
665 year += data.modifier();
670 docstring const BiblioInfo::getInfo(docstring const & key,
671 Buffer const & buf, bool richtext) const
673 BiblioInfo::const_iterator it = find(key);
676 BibTeXInfo const & data = it->second;
677 BibTeXInfo const * xrefptr = 0;
678 docstring const xref = data.getXRef();
680 BiblioInfo::const_iterator const xrefit = find(xref);
682 xrefptr = &(xrefit->second);
684 return data.getInfo(xrefptr, buf, richtext);
688 bool BiblioInfo::isBibtex(docstring const & key) const
690 BiblioInfo::const_iterator it = find(key);
693 return it->second.isBibTeX();
698 vector<docstring> const BiblioInfo::getCiteStrings(
699 docstring const & key, Buffer const & buf) const
701 CiteEngine const engine = buf.params().citeEngine();
702 if (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL)
703 return getNumericalStrings(key, buf);
705 return getAuthorYearStrings(key, buf);
709 vector<docstring> const BiblioInfo::getNumericalStrings(
710 docstring const & key, Buffer const & buf) const
713 return vector<docstring>();
715 docstring const author = getAbbreviatedAuthor(key);
716 docstring const year = getYear(key);
717 if (author.empty() || year.empty())
718 return vector<docstring>();
720 vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
722 vector<docstring> vec(styles.size());
723 for (size_t i = 0; i != vec.size(); ++i) {
729 str = from_ascii("[#ID]");
733 str = _("Add to bibliography only.");
737 str = author + " [#ID]";
741 str = author + " #ID";
745 str = from_ascii("#ID");
757 str = '(' + year + ')';
768 vector<docstring> const BiblioInfo::getAuthorYearStrings(
769 docstring const & key, Buffer const & buf) const
772 return vector<docstring>();
774 docstring const author = getAbbreviatedAuthor(key);
775 docstring const year = getYear(key);
776 if (author.empty() || year.empty())
777 return vector<docstring>();
779 vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
781 vector<docstring> vec(styles.size());
782 for (size_t i = 0; i != vec.size(); ++i) {
787 // jurabib only: Author/Annotator
788 // (i.e. the "before" field, 2nd opt arg)
789 str = author + "/<" + _("before") + '>';
793 str = _("Add to bibliography only.");
797 str = author + " (" + year + ')';
801 str = '(' + author + ", " + year + ')';
805 str = author + ' ' + year ;
809 str = author + ", " + year ;
821 str = '(' + year + ')';
830 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
832 bimap_.insert(info.begin(), info.end());
833 field_names_.insert(info.field_names_.begin(), info.field_names_.end());
834 entry_types_.insert(info.entry_types_.begin(), info.entry_types_.end());
839 // used in xhtml to sort a list of BibTeXInfo objects
840 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
842 docstring const lauth = lhs->getAbbreviatedAuthor();
843 docstring const rauth = rhs->getAbbreviatedAuthor();
844 docstring const lyear = lhs->getYear();
845 docstring const ryear = rhs->getYear();
846 docstring const ltitl = lhs->operator[]("title");
847 docstring const rtitl = rhs->operator[]("title");
848 return (lauth < rauth)
849 || (lauth == rauth && lyear < ryear)
850 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
855 void BiblioInfo::collectCitedEntries(Buffer const & buf)
857 cited_entries_.clear();
858 // We are going to collect all the citation keys used in the document,
859 // getting them from the TOC.
860 // FIXME We may want to collect these differently, in the first case,
861 // so that we might have them in order of appearance.
862 set<docstring> citekeys;
863 Toc const & toc = buf.tocBackend().toc("citation");
864 Toc::const_iterator it = toc.begin();
865 Toc::const_iterator const en = toc.end();
866 for (; it != en; ++it) {
867 if (it->str().empty())
869 vector<docstring> const keys = getVectorFromString(it->str());
870 citekeys.insert(keys.begin(), keys.end());
872 if (citekeys.empty())
875 // We have a set of the keys used in this document.
876 // We will now convert it to a list of the BibTeXInfo objects used in
878 vector<BibTeXInfo const *> bi;
879 set<docstring>::const_iterator cit = citekeys.begin();
880 set<docstring>::const_iterator const cen = citekeys.end();
881 for (; cit != cen; ++cit) {
882 BiblioInfo::const_iterator const bt = find(*cit);
883 if (bt == end() || !bt->second.isBibTeX())
885 bi.push_back(&(bt->second));
888 sort(bi.begin(), bi.end(), lSorter);
890 // Now we can write the sorted keys
891 vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
892 vector<BibTeXInfo const *>::const_iterator ben = bi.end();
893 for (; bit != ben; ++bit)
894 cited_entries_.push_back((*bit)->key());
898 void BiblioInfo::makeCitationLabels(Buffer const & buf)
900 collectCitedEntries(buf);
901 CiteEngine const engine = buf.params().citeEngine();
903 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
907 // used to remember the last one we saw
908 // we'll be comparing entries to see if we need to add
909 // modifiers, like "1984a"
910 map<docstring, BibTeXInfo>::iterator last;
912 vector<docstring>::const_iterator it = cited_entries_.begin();
913 vector<docstring>::const_iterator const en = cited_entries_.end();
914 for (; it != en; ++it) {
915 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
916 // this shouldn't happen, but...
917 if (biit == bimap_.end())
918 // ...fail gracefully, anyway.
920 BibTeXInfo & entry = biit->second;
922 docstring const num = convert<docstring>(++keynumber);
923 entry.setCiteNumber(num);
925 if (it != cited_entries_.begin()
926 && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
927 // we access the year via getYear() so as to get it from the xref,
928 // if we need to do so
929 && getYear(entry.key()) == getYear(last->second.key())) {
931 // so the last one should have been 'a'
932 last->second.setModifier('a');
934 } else if (modifier == 'z')
941 entry.setModifier(modifier);
942 // remember the last one
949 //////////////////////////////////////////////////////////////////////
953 //////////////////////////////////////////////////////////////////////
958 char const * const citeCommands[] = {
959 "cite", "citet", "citep", "citealt", "citealp",
960 "citeauthor", "citeyear", "citeyearpar", "nocite" };
962 unsigned int const nCiteCommands =
963 sizeof(citeCommands) / sizeof(char *);
965 CiteStyle const citeStylesArray[] = {
966 CITE, CITET, CITEP, CITEALT, CITEALP,
967 CITEAUTHOR, CITEYEAR, CITEYEARPAR, NOCITE };
969 unsigned int const nCiteStyles =
970 sizeof(citeStylesArray) / sizeof(CiteStyle);
972 CiteStyle const citeStylesFull[] = {
973 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
975 unsigned int const nCiteStylesFull =
976 sizeof(citeStylesFull) / sizeof(CiteStyle);
978 CiteStyle const citeStylesUCase[] = {
979 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
981 unsigned int const nCiteStylesUCase =
982 sizeof(citeStylesUCase) / sizeof(CiteStyle);
987 CitationStyle citationStyleFromString(string const & command)
993 string cmd = command;
995 s.forceUpperCase = true;
999 size_t const n = cmd.size() - 1;
1000 if (cmd != "cite" && cmd[n] == '*') {
1002 cmd = cmd.substr(0, n);
1005 char const * const * const last = citeCommands + nCiteCommands;
1006 char const * const * const ptr = find(citeCommands, last, cmd);
1009 size_t idx = ptr - citeCommands;
1010 s.style = citeStylesArray[idx];
1016 string citationStyleToString(const CitationStyle & s)
1018 string cite = citeCommands[s.style];
1020 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
1021 if (std::find(citeStylesFull, last, s.style) != last)
1025 if (s.forceUpperCase) {
1026 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
1027 if (std::find(citeStylesUCase, last, s.style) != last)
1034 vector<CiteStyle> citeStyles(CiteEngine engine)
1036 unsigned int nStyles = 0;
1037 unsigned int start = 0;
1044 case ENGINE_NATBIB_AUTHORYEAR:
1045 case ENGINE_NATBIB_NUMERICAL:
1046 nStyles = nCiteStyles - 1;
1049 case ENGINE_JURABIB:
1050 nStyles = nCiteStyles;
1055 vector<CiteStyle> styles(nStyles);
1058 for (; i != styles.size(); ++i, ++j)
1059 styles[i] = citeStylesArray[j];