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"
21 #include "Paragraph.h"
22 #include "TocBackend.h"
24 #include "insets/Inset.h"
25 #include "insets/InsetBibitem.h"
26 #include "insets/InsetBibtex.h"
27 #include "insets/InsetInclude.h"
29 #include "support/convert.h"
30 #include "support/docstream.h"
31 #include "support/gettext.h"
32 #include "support/lassert.h"
33 #include "support/lstrings.h"
34 #include "support/textutils.h"
36 #include "boost/regex.hpp"
41 using namespace lyx::support;
48 // gets the "family name" from an author-type string
49 docstring familyName(docstring const & name)
54 // first we look for a comma, and take the last name to be everything
55 // preceding the right-most one, so that we also get the "jr" part.
56 docstring::size_type idx = name.rfind(',');
57 if (idx != docstring::npos)
58 return ltrim(name.substr(0, idx));
60 // OK, so now we want to look for the last name. We're going to
61 // include the "von" part. This isn't perfect.
62 // Split on spaces, to get various tokens.
63 vector<docstring> pieces = getVectorFromString(name, from_ascii(" "));
64 // If we only get two, assume the last one is the last name
65 if (pieces.size() <= 2)
68 // Now we look for the first token that begins with a lower case letter.
69 vector<docstring>::const_iterator it = pieces.begin();
70 vector<docstring>::const_iterator en = pieces.end();
71 for (; it != en; ++it) {
72 if ((*it).size() == 0)
74 char_type const c = (*it)[0];
79 if (it == en) // we never found a "von"
82 // reconstruct what we need to return
85 for (; it != en; ++it) {
95 // converts a string containing LaTeX commands into unicode
97 docstring convertLaTeXCommands(docstring const & str)
102 bool scanning_cmd = false;
103 bool scanning_math = false;
104 bool escaped = false; // used to catch \$, etc.
106 char_type const ch = val[0];
108 // if we're scanning math, we output everything until we
109 // find an unescaped $, at which point we break out.
116 scanning_math = false;
122 // if we're scanning a command name, then we just
123 // discard characters until we hit something that
126 if (isAlphaASCII(ch)) {
131 // so we're done with this command.
132 // now we fall through and check this character.
133 scanning_cmd = false;
136 // was the last character a \? If so, then this is something like:
137 // \\ or \$, so we'll just output it. That's probably not always right...
139 // exception: output \, as THIN SPACE
141 ret.push_back(0x2009);
152 scanning_math = true;
156 // we just ignore braces
157 if (ch == '{' || ch == '}') {
162 // we're going to check things that look like commands, so if
163 // this doesn't, just output it.
170 // ok, could be a command of some sort
171 // let's see if it corresponds to some unicode
172 // unicodesymbols has things in the form: \"{u},
173 // whereas we may see things like: \"u. So we'll
174 // look for that and change it, if necessary.
175 static boost::regex const reg("^\\\\\\W\\w");
176 if (boost::regex_search(to_utf8(val), reg)) {
177 val.insert(3, from_ascii("}"));
178 val.insert(2, from_ascii("{"));
181 docstring const cnvtd = Encodings::fromLaTeXCommand(val, rem,
182 Encodings::TEXT_CMD);
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() 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 // 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 (authors.size() == 2)
241 return bformat(_("%1$s and %2$s"),
242 familyName(authors[0]), familyName(authors[1]));
244 if (authors.size() > 2)
245 return bformat(_("%1$s et al."), familyName(authors[0]));
247 return familyName(authors[0]);
251 docstring const BibTeXInfo::getYear() const
254 return operator[]("year");
256 docstring const opt = label();
261 docstring tmp = split(opt, authors, '(');
263 // we don't have author (year)
266 tmp = split(tmp, year, ')');
271 docstring const BibTeXInfo::getXRef() const
275 return operator[]("crossref");
279 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref) const
285 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
291 // This could be made a lot better using the entry_type_
292 // field to customize the output based upon entry type.
294 // Search for all possible "required" fields
295 docstring author = getValueForKey("author", xref);
297 author = getValueForKey("editor", xref);
299 docstring year = getValueForKey("year", xref);
300 docstring title = getValueForKey("title", xref);
301 docstring docLoc = getValueForKey("pages", xref);
302 if (docLoc.empty()) {
303 docLoc = getValueForKey("chapter", xref);
305 docLoc = _("Ch. ") + docLoc;
307 docLoc = _("pp. ") + docLoc;
310 docstring media = getValueForKey("journal", xref);
312 media = getValueForKey("publisher", xref);
314 media = getValueForKey("school", xref);
316 media = getValueForKey("institution");
319 docstring volume = getValueForKey("volume", xref);
321 odocstringstream result;
323 result << author << ", ";
327 result << ", " << media;
329 result << " (" << year << ")";
331 result << ", " << docLoc;
333 docstring const result_str = rtrim(result.str());
334 if (!result_str.empty()) {
335 info_ = convertLaTeXCommands(result_str);
339 // This should never happen (or at least be very unusual!)
340 static docstring e = docstring();
345 docstring const & BibTeXInfo::operator[](docstring const & field) const
347 BibTeXInfo::const_iterator it = find(field);
350 static docstring const empty_value = docstring();
355 docstring const & BibTeXInfo::operator[](string const & field) const
357 return operator[](from_ascii(field));
361 docstring BibTeXInfo::getValueForKey(string const & key,
362 BibTeXInfo const * const xref) const
364 docstring const ret = operator[](key);
365 if (!ret.empty() || !xref)
371 //////////////////////////////////////////////////////////////////////
375 //////////////////////////////////////////////////////////////////////
378 // A functor for use with sort, leading to case insensitive sorting
379 class compareNoCase: public binary_function<docstring, docstring, bool>
382 bool operator()(docstring const & s1, docstring const & s2) const {
383 return compare_no_case(s1, s2) < 0;
389 vector<docstring> const BiblioInfo::getKeys() const
391 vector<docstring> bibkeys;
392 BiblioInfo::const_iterator it = begin();
393 for (; it != end(); ++it)
394 bibkeys.push_back(it->first);
395 sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
400 vector<docstring> const BiblioInfo::getFields() const
402 vector<docstring> bibfields;
403 set<docstring>::const_iterator it = field_names_.begin();
404 set<docstring>::const_iterator end = field_names_.end();
405 for (; it != end; ++it)
406 bibfields.push_back(*it);
407 sort(bibfields.begin(), bibfields.end());
412 vector<docstring> const BiblioInfo::getEntries() const
414 vector<docstring> bibentries;
415 set<docstring>::const_iterator it = entry_types_.begin();
416 set<docstring>::const_iterator end = entry_types_.end();
417 for (; it != end; ++it)
418 bibentries.push_back(*it);
419 sort(bibentries.begin(), bibentries.end());
424 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
426 BiblioInfo::const_iterator it = find(key);
429 BibTeXInfo const & data = it->second;
430 return data.getAbbreviatedAuthor();
434 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
436 BiblioInfo::const_iterator it = find(key);
439 BibTeXInfo const & data = it->second;
440 return data.citeNumber();
444 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier) const
446 BiblioInfo::const_iterator it = find(key);
449 BibTeXInfo const & data = it->second;
450 docstring year = data.getYear();
452 // let's try the crossref
453 docstring const xref = data.getXRef();
455 return _("No year"); // no luck
456 BiblioInfo::const_iterator const xrefit = find(xref);
458 return _("No year"); // no luck again
459 BibTeXInfo const & xref_data = xrefit->second;
460 year = xref_data.getYear();
462 if (use_modifier && data.modifier() != 0)
463 year += data.modifier();
468 docstring const BiblioInfo::getInfo(docstring const & key) const
470 BiblioInfo::const_iterator it = find(key);
473 BibTeXInfo const & data = it->second;
474 BibTeXInfo const * xrefptr = 0;
475 docstring const xref = data.getXRef();
477 BiblioInfo::const_iterator const xrefit = find(xref);
479 xrefptr = &(xrefit->second);
481 return data.getInfo(xrefptr);
485 vector<docstring> const BiblioInfo::getCiteStrings(
486 docstring const & key, Buffer const & buf) const
488 CiteEngine const engine = buf.params().citeEngine();
489 if (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL)
490 return getNumericalStrings(key, buf);
492 return getAuthorYearStrings(key, buf);
496 vector<docstring> const BiblioInfo::getNumericalStrings(
497 docstring const & key, Buffer const & buf) const
500 return vector<docstring>();
502 docstring const author = getAbbreviatedAuthor(key);
503 docstring const year = getYear(key);
504 if (author.empty() || year.empty())
505 return vector<docstring>();
507 vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
509 vector<docstring> vec(styles.size());
510 for (size_t i = 0; i != vec.size(); ++i) {
516 str = from_ascii("[#ID]");
520 str = _("Add to bibliography only.");
524 str = author + " [#ID]";
528 str = author + " #ID";
532 str = from_ascii("#ID");
544 str = '(' + year + ')';
555 vector<docstring> const BiblioInfo::getAuthorYearStrings(
556 docstring const & key, Buffer const & buf) const
559 return vector<docstring>();
561 docstring const author = getAbbreviatedAuthor(key);
562 docstring const year = getYear(key);
563 if (author.empty() || year.empty())
564 return vector<docstring>();
566 vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
568 vector<docstring> vec(styles.size());
569 for (size_t i = 0; i != vec.size(); ++i) {
574 // jurabib only: Author/Annotator
575 // (i.e. the "before" field, 2nd opt arg)
576 str = author + "/<" + _("before") + '>';
580 str = _("Add to bibliography only.");
584 str = author + " (" + year + ')';
588 str = '(' + author + ", " + year + ')';
592 str = author + ' ' + year ;
596 str = author + ", " + year ;
608 str = '(' + year + ')';
617 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
619 bimap_.insert(info.begin(), info.end());
624 // used in xhtml to sort a list of BibTeXInfo objects
625 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
627 docstring const lauth = lhs->getAbbreviatedAuthor();
628 docstring const rauth = rhs->getAbbreviatedAuthor();
629 docstring const lyear = lhs->getYear();
630 docstring const ryear = rhs->getYear();
631 docstring const ltitl = lhs->operator[]("title");
632 docstring const rtitl = rhs->operator[]("title");
633 return (lauth < rauth)
634 || (lauth == rauth && lyear < ryear)
635 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
640 void BiblioInfo::collectCitedEntries(Buffer const & buf)
642 cited_entries_.clear();
643 // We are going to collect all the citation keys used in the document,
644 // getting them from the TOC.
645 // FIXME We may want to collect these differently, in the first case,
646 // so that we might have them in order of appearance.
647 set<docstring> citekeys;
648 Toc const & toc = buf.tocBackend().toc("citation");
649 Toc::const_iterator it = toc.begin();
650 Toc::const_iterator const en = toc.end();
651 for (; it != en; ++it) {
652 if (it->str().empty())
654 vector<docstring> const keys = getVectorFromString(it->str());
655 citekeys.insert(keys.begin(), keys.end());
657 if (citekeys.empty())
660 // We have a set of the keys used in this document.
661 // We will now convert it to a list of the BibTeXInfo objects used in
663 vector<BibTeXInfo const *> bi;
664 set<docstring>::const_iterator cit = citekeys.begin();
665 set<docstring>::const_iterator const cen = citekeys.end();
666 for (; cit != cen; ++cit) {
667 BiblioInfo::const_iterator const bt = find(*cit);
668 if (bt == end() || !bt->second.isBibTeX())
670 bi.push_back(&(bt->second));
673 sort(bi.begin(), bi.end(), lSorter);
675 // Now we can write the sorted keys
676 vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
677 vector<BibTeXInfo const *>::const_iterator ben = bi.end();
678 for (; bit != ben; ++bit)
679 cited_entries_.push_back((*bit)->key());
683 void BiblioInfo::makeCitationLabels(Buffer const & buf)
685 collectCitedEntries(buf);
686 CiteEngine const engine = buf.params().citeEngine();
688 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
692 // used to remember the last one we saw
693 // we'll be comparing entries to see if we need to add
694 // modifiers, like "1984a"
695 map<docstring, BibTeXInfo>::iterator last;
697 vector<docstring>::const_iterator it = cited_entries_.begin();
698 vector<docstring>::const_iterator const en = cited_entries_.end();
699 for (; it != en; ++it) {
700 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
701 // this shouldn't happen, but...
702 if (biit == bimap_.end())
703 // ...fail gracefully, anyway.
705 BibTeXInfo & entry = biit->second;
707 docstring const num = convert<docstring>(++keynumber);
708 entry.setCiteNumber(num);
710 if (it != cited_entries_.begin()
711 && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
712 // we access the year via getYear() so as to get it from the xref,
713 // if we need to do so
714 && getYear(entry.key()) == getYear(last->second.key())) {
716 // so the last one should have been 'a'
717 last->second.setModifier('a');
719 } else if (modifier == 'z')
726 entry.setModifier(modifier);
727 // remember the last one
734 //////////////////////////////////////////////////////////////////////
738 //////////////////////////////////////////////////////////////////////
743 char const * const citeCommands[] = {
744 "cite", "citet", "citep", "citealt", "citealp",
745 "citeauthor", "citeyear", "citeyearpar", "nocite" };
747 unsigned int const nCiteCommands =
748 sizeof(citeCommands) / sizeof(char *);
750 CiteStyle const citeStylesArray[] = {
751 CITE, CITET, CITEP, CITEALT, CITEALP,
752 CITEAUTHOR, CITEYEAR, CITEYEARPAR, NOCITE };
754 unsigned int const nCiteStyles =
755 sizeof(citeStylesArray) / sizeof(CiteStyle);
757 CiteStyle const citeStylesFull[] = {
758 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
760 unsigned int const nCiteStylesFull =
761 sizeof(citeStylesFull) / sizeof(CiteStyle);
763 CiteStyle const citeStylesUCase[] = {
764 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
766 unsigned int const nCiteStylesUCase =
767 sizeof(citeStylesUCase) / sizeof(CiteStyle);
772 CitationStyle citationStyleFromString(string const & command)
778 string cmd = command;
780 s.forceUpperCase = true;
784 size_t const n = cmd.size() - 1;
785 if (cmd != "cite" && cmd[n] == '*') {
787 cmd = cmd.substr(0, n);
790 char const * const * const last = citeCommands + nCiteCommands;
791 char const * const * const ptr = find(citeCommands, last, cmd);
794 size_t idx = ptr - citeCommands;
795 s.style = citeStylesArray[idx];
801 string citationStyleToString(const CitationStyle & s)
803 string cite = citeCommands[s.style];
805 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
806 if (std::find(citeStylesFull, last, s.style) != last)
810 if (s.forceUpperCase) {
811 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
812 if (std::find(citeStylesUCase, last, s.style) != last)
819 vector<CiteStyle> citeStyles(CiteEngine engine)
821 unsigned int nStyles = 0;
822 unsigned int start = 0;
829 case ENGINE_NATBIB_AUTHORYEAR:
830 case ENGINE_NATBIB_NUMERICAL:
831 nStyles = nCiteStyles - 1;
835 nStyles = nCiteStyles;
840 vector<CiteStyle> styles(nStyles);
843 for (; i != styles.size(); ++i, ++j)
844 styles[i] = citeStylesArray[j];