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 split(opt, authors, '(');
224 docstring author = convertLaTeXCommands(operator[]("author"));
225 if (author.empty()) {
226 author = convertLaTeXCommands(operator[]("editor"));
231 // OK, we've got some names. Let's format them.
232 // Try to split the author list on " and "
233 vector<docstring> const authors =
234 getVectorFromString(author, from_ascii(" and "));
236 if (authors.size() == 2)
237 return bformat(_("%1$s and %2$s"),
238 familyName(authors[0]), familyName(authors[1]));
240 if (authors.size() > 2)
241 return bformat(_("%1$s et al."), familyName(authors[0]));
243 return familyName(authors[0]);
247 docstring const BibTeXInfo::getYear() const
250 return operator[]("year");
252 docstring const opt = label();
257 docstring const tmp = split(opt, authors, '(');
259 split(tmp, year, ')');
264 docstring const BibTeXInfo::getXRef() const
268 return operator[]("crossref");
272 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref) const
278 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
284 // This could be made a lot better using the entry_type_
285 // field to customize the output based upon entry type.
287 // Search for all possible "required" fields
288 docstring author = getValueForKey("author", xref);
290 author = getValueForKey("editor", xref);
292 docstring year = getValueForKey("year", xref);
293 docstring title = getValueForKey("title", xref);
294 docstring docLoc = getValueForKey("pages", xref);
295 if (docLoc.empty()) {
296 docLoc = getValueForKey("chapter", xref);
298 docLoc = _("Ch. ") + docLoc;
300 docLoc = _("pp. ") + docLoc;
303 docstring media = getValueForKey("journal", xref);
305 media = getValueForKey("publisher", xref);
307 media = getValueForKey("school", xref);
309 media = getValueForKey("institution");
312 docstring volume = getValueForKey("volume", xref);
314 odocstringstream result;
316 result << author << ", ";
320 result << ", " << media;
322 result << " (" << year << ")";
324 result << ", " << docLoc;
326 docstring const result_str = rtrim(result.str());
327 if (!result_str.empty()) {
328 info_ = convertLaTeXCommands(result_str);
332 // This should never happen (or at least be very unusual!)
333 static docstring e = docstring();
338 docstring const & BibTeXInfo::operator[](docstring const & field) const
340 BibTeXInfo::const_iterator it = find(field);
343 static docstring const empty_value = docstring();
348 docstring const & BibTeXInfo::operator[](string const & field) const
350 return operator[](from_ascii(field));
354 docstring BibTeXInfo::getValueForKey(string const & key,
355 BibTeXInfo const * const xref) const
357 docstring const ret = operator[](key);
358 if (!ret.empty() || !xref)
364 //////////////////////////////////////////////////////////////////////
368 //////////////////////////////////////////////////////////////////////
371 // A functor for use with sort, leading to case insensitive sorting
372 class compareNoCase: public binary_function<docstring, docstring, bool>
375 bool operator()(docstring const & s1, docstring const & s2) const {
376 return compare_no_case(s1, s2) < 0;
382 vector<docstring> const BiblioInfo::getKeys() const
384 vector<docstring> bibkeys;
385 BiblioInfo::const_iterator it = begin();
386 for (; it != end(); ++it)
387 bibkeys.push_back(it->first);
388 sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
393 vector<docstring> const BiblioInfo::getFields() const
395 vector<docstring> bibfields;
396 set<docstring>::const_iterator it = field_names_.begin();
397 set<docstring>::const_iterator end = field_names_.end();
398 for (; it != end; ++it)
399 bibfields.push_back(*it);
400 sort(bibfields.begin(), bibfields.end());
405 vector<docstring> const BiblioInfo::getEntries() const
407 vector<docstring> bibentries;
408 set<docstring>::const_iterator it = entry_types_.begin();
409 set<docstring>::const_iterator end = entry_types_.end();
410 for (; it != end; ++it)
411 bibentries.push_back(*it);
412 sort(bibentries.begin(), bibentries.end());
417 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
419 BiblioInfo::const_iterator it = find(key);
422 BibTeXInfo const & data = it->second;
423 return data.getAbbreviatedAuthor();
427 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
429 BiblioInfo::const_iterator it = find(key);
432 BibTeXInfo const & data = it->second;
433 return data.citeNumber();
437 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier) const
439 BiblioInfo::const_iterator it = find(key);
442 BibTeXInfo const & data = it->second;
443 docstring year = data.getYear();
445 // let's try the crossref
446 docstring const xref = data.getXRef();
448 return _("No year"); // no luck
449 BiblioInfo::const_iterator const xrefit = find(xref);
451 return _("No year"); // no luck again
452 BibTeXInfo const & xref_data = xrefit->second;
453 year = xref_data.getYear();
455 if (use_modifier && data.modifier() != 0)
456 year += data.modifier();
461 docstring const BiblioInfo::getInfo(docstring const & key) const
463 BiblioInfo::const_iterator it = find(key);
466 BibTeXInfo const & data = it->second;
467 BibTeXInfo const * xrefptr = 0;
468 docstring const xref = data.getXRef();
470 BiblioInfo::const_iterator const xrefit = find(xref);
472 xrefptr = &(xrefit->second);
474 return data.getInfo(xrefptr);
478 vector<docstring> const BiblioInfo::getCiteStrings(
479 docstring const & key, Buffer const & buf) const
481 CiteEngine const engine = buf.params().citeEngine();
482 if (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL)
483 return getNumericalStrings(key, buf);
485 return getAuthorYearStrings(key, buf);
489 vector<docstring> const BiblioInfo::getNumericalStrings(
490 docstring const & key, Buffer const & buf) const
493 return vector<docstring>();
495 docstring const author = getAbbreviatedAuthor(key);
496 docstring const year = getYear(key);
497 if (author.empty() || year.empty())
498 return vector<docstring>();
500 vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
502 vector<docstring> vec(styles.size());
503 for (size_t i = 0; i != vec.size(); ++i) {
509 str = from_ascii("[#ID]");
513 str = _("Add to bibliography only.");
517 str = author + " [#ID]";
521 str = author + " #ID";
525 str = from_ascii("#ID");
537 str = '(' + year + ')';
548 vector<docstring> const BiblioInfo::getAuthorYearStrings(
549 docstring const & key, Buffer const & buf) const
552 return vector<docstring>();
554 docstring const author = getAbbreviatedAuthor(key);
555 docstring const year = getYear(key);
556 if (author.empty() || year.empty())
557 return vector<docstring>();
559 vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
561 vector<docstring> vec(styles.size());
562 for (size_t i = 0; i != vec.size(); ++i) {
567 // jurabib only: Author/Annotator
568 // (i.e. the "before" field, 2nd opt arg)
569 str = author + "/<" + _("before") + '>';
573 str = _("Add to bibliography only.");
577 str = author + " (" + year + ')';
581 str = '(' + author + ", " + year + ')';
585 str = author + ' ' + year ;
589 str = author + ", " + year ;
601 str = '(' + year + ')';
610 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
612 bimap_.insert(info.begin(), info.end());
617 // used in xhtml to sort a list of BibTeXInfo objects
618 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
620 docstring const lauth = lhs->getAbbreviatedAuthor();
621 docstring const rauth = rhs->getAbbreviatedAuthor();
622 docstring const lyear = lhs->getYear();
623 docstring const ryear = rhs->getYear();
624 docstring const ltitl = lhs->operator[]("title");
625 docstring const rtitl = rhs->operator[]("title");
626 return (lauth < rauth)
627 || (lauth == rauth && lyear < ryear)
628 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
633 void BiblioInfo::collectCitedEntries(Buffer const & buf)
635 cited_entries_.clear();
636 // We are going to collect all the citation keys used in the document,
637 // getting them from the TOC.
638 // FIXME We may want to collect these differently, in the first case,
639 // so that we might have them in order of appearance.
640 set<docstring> citekeys;
641 Toc const & toc = buf.tocBackend().toc("citation");
642 Toc::const_iterator it = toc.begin();
643 Toc::const_iterator const en = toc.end();
644 for (; it != en; ++it) {
645 if (it->str().empty())
647 vector<docstring> const keys = getVectorFromString(it->str());
648 citekeys.insert(keys.begin(), keys.end());
650 if (citekeys.empty())
653 // We have a set of the keys used in this document.
654 // We will now convert it to a list of the BibTeXInfo objects used in
656 vector<BibTeXInfo const *> bi;
657 set<docstring>::const_iterator cit = citekeys.begin();
658 set<docstring>::const_iterator const cen = citekeys.end();
659 for (; cit != cen; ++cit) {
660 BiblioInfo::const_iterator const bt = find(*cit);
661 if (bt == end() || !bt->second.isBibTeX())
663 bi.push_back(&(bt->second));
666 sort(bi.begin(), bi.end(), lSorter);
668 // Now we can write the sorted keys
669 vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
670 vector<BibTeXInfo const *>::const_iterator ben = bi.end();
671 for (; bit != ben; ++bit)
672 cited_entries_.push_back((*bit)->key());
676 void BiblioInfo::makeCitationLabels(Buffer const & buf)
678 collectCitedEntries(buf);
679 CiteEngine const engine = buf.params().citeEngine();
681 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
685 // used to remember the last one we saw
686 // we'll be comparing entries to see if we need to add
687 // modifiers, like "1984a"
688 map<docstring, BibTeXInfo>::iterator last;
690 vector<docstring>::const_iterator it = cited_entries_.begin();
691 vector<docstring>::const_iterator const en = cited_entries_.end();
692 for (; it != en; ++it) {
693 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
694 // this shouldn't happen, but...
695 if (biit == bimap_.end())
696 // ...fail gracefully, anyway.
698 BibTeXInfo & entry = biit->second;
700 docstring const num = convert<docstring>(++keynumber);
701 entry.setCiteNumber(num);
703 if (it != cited_entries_.begin()
704 && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
705 // we access the year via getYear() so as to get it from the xref,
706 // if we need to do so
707 && getYear(entry.key()) == getYear(last->second.key())) {
709 // so the last one should have been 'a'
710 last->second.setModifier('a');
712 } else if (modifier == 'z')
719 entry.setModifier(modifier);
720 // remember the last one
727 //////////////////////////////////////////////////////////////////////
731 //////////////////////////////////////////////////////////////////////
736 char const * const citeCommands[] = {
737 "cite", "citet", "citep", "citealt", "citealp",
738 "citeauthor", "citeyear", "citeyearpar", "nocite" };
740 unsigned int const nCiteCommands =
741 sizeof(citeCommands) / sizeof(char *);
743 CiteStyle const citeStylesArray[] = {
744 CITE, CITET, CITEP, CITEALT, CITEALP,
745 CITEAUTHOR, CITEYEAR, CITEYEARPAR, NOCITE };
747 unsigned int const nCiteStyles =
748 sizeof(citeStylesArray) / sizeof(CiteStyle);
750 CiteStyle const citeStylesFull[] = {
751 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
753 unsigned int const nCiteStylesFull =
754 sizeof(citeStylesFull) / sizeof(CiteStyle);
756 CiteStyle const citeStylesUCase[] = {
757 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
759 unsigned int const nCiteStylesUCase =
760 sizeof(citeStylesUCase) / sizeof(CiteStyle);
765 CitationStyle citationStyleFromString(string const & command)
771 string cmd = command;
773 s.forceUpperCase = true;
777 size_t const n = cmd.size() - 1;
778 if (cmd != "cite" && cmd[n] == '*') {
780 cmd = cmd.substr(0, n);
783 char const * const * const last = citeCommands + nCiteCommands;
784 char const * const * const ptr = find(citeCommands, last, cmd);
787 size_t idx = ptr - citeCommands;
788 s.style = citeStylesArray[idx];
794 string citationStyleToString(const CitationStyle & s)
796 string cite = citeCommands[s.style];
798 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
799 if (std::find(citeStylesFull, last, s.style) != last)
803 if (s.forceUpperCase) {
804 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
805 if (std::find(citeStylesUCase, last, s.style) != last)
812 vector<CiteStyle> citeStyles(CiteEngine engine)
814 unsigned int nStyles = 0;
815 unsigned int start = 0;
822 case ENGINE_NATBIB_AUTHORYEAR:
823 case ENGINE_NATBIB_NUMERICAL:
824 nStyles = nCiteStyles - 1;
828 nStyles = nCiteStyles;
833 vector<CiteStyle> styles(nStyles);
836 for (; i != styles.size(); ++i, ++j)
837 styles[i] = citeStylesArray[j];