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_()
211 docstring const BibTeXInfo::getAbbreviatedAuthor() const
214 docstring const opt = label();
219 split(opt, authors, '(');
223 docstring author = convertLaTeXCommands(operator[]("author"));
224 if (author.empty()) {
225 author = convertLaTeXCommands(operator[]("editor"));
230 // OK, we've got some names. Let's format them.
231 // Try to split the author list on " and "
232 vector<docstring> const authors =
233 getVectorFromString(author, from_ascii(" and "));
235 if (authors.size() == 2)
236 return bformat(_("%1$s and %2$s"),
237 familyName(authors[0]), familyName(authors[1]));
239 if (authors.size() > 2)
240 return bformat(_("%1$s et al."), familyName(authors[0]));
242 return familyName(authors[0]);
246 docstring const BibTeXInfo::getYear() const
249 return operator[]("year");
251 docstring const opt = label();
256 docstring const tmp = split(opt, authors, '(');
258 split(tmp, year, ')');
263 docstring const BibTeXInfo::getXRef() const
267 return operator[]("crossref");
271 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref) const
277 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
283 // This could be made a lot better using the entry_type_
284 // field to customize the output based upon entry type.
286 // Search for all possible "required" fields
287 docstring author = getValueForKey("author", xref);
289 author = getValueForKey("editor", xref);
291 docstring year = getValueForKey("year", xref);
292 docstring title = getValueForKey("title", xref);
293 docstring docLoc = getValueForKey("pages", xref);
294 if (docLoc.empty()) {
295 docLoc = getValueForKey("chapter", xref);
297 docLoc = _("Ch. ") + docLoc;
299 docLoc = _("pp. ") + docLoc;
302 docstring media = getValueForKey("journal", xref);
304 media = getValueForKey("publisher", xref);
306 media = getValueForKey("school", xref);
308 media = getValueForKey("institution");
311 docstring volume = getValueForKey("volume", xref);
313 odocstringstream result;
315 result << author << ", ";
319 result << ", " << media;
321 result << " (" << year << ")";
323 result << ", " << docLoc;
325 docstring const result_str = rtrim(result.str());
326 if (!result_str.empty()) {
327 info_ = convertLaTeXCommands(result_str);
331 // This should never happen (or at least be very unusual!)
332 static docstring e = docstring();
337 docstring const & BibTeXInfo::operator[](docstring const & field) const
339 BibTeXInfo::const_iterator it = find(field);
342 static docstring const empty_value = docstring();
347 docstring const & BibTeXInfo::operator[](string const & field) const
349 return operator[](from_ascii(field));
353 docstring BibTeXInfo::getValueForKey(string const & key,
354 BibTeXInfo const * const xref) const
356 docstring const ret = operator[](key);
357 if (!ret.empty() || !xref)
363 //////////////////////////////////////////////////////////////////////
367 //////////////////////////////////////////////////////////////////////
370 // A functor for use with sort, leading to case insensitive sorting
371 class compareNoCase: public binary_function<docstring, docstring, bool>
374 bool operator()(docstring const & s1, docstring const & s2) const {
375 return compare_no_case(s1, s2) < 0;
381 vector<docstring> const BiblioInfo::getKeys() const
383 vector<docstring> bibkeys;
384 BiblioInfo::const_iterator it = begin();
385 for (; it != end(); ++it)
386 bibkeys.push_back(it->first);
387 sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
392 vector<docstring> const BiblioInfo::getFields() const
394 vector<docstring> bibfields;
395 set<docstring>::const_iterator it = field_names_.begin();
396 set<docstring>::const_iterator end = field_names_.end();
397 for (; it != end; ++it)
398 bibfields.push_back(*it);
399 sort(bibfields.begin(), bibfields.end());
404 vector<docstring> const BiblioInfo::getEntries() const
406 vector<docstring> bibentries;
407 set<docstring>::const_iterator it = entry_types_.begin();
408 set<docstring>::const_iterator end = entry_types_.end();
409 for (; it != end; ++it)
410 bibentries.push_back(*it);
411 sort(bibentries.begin(), bibentries.end());
416 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
418 BiblioInfo::const_iterator it = find(key);
421 BibTeXInfo const & data = it->second;
422 return data.getAbbreviatedAuthor();
426 docstring const BiblioInfo::getYear(docstring const & key) const
428 BiblioInfo::const_iterator it = find(key);
431 BibTeXInfo const & data = it->second;
432 docstring year = data.getYear();
435 // let's try the crossref
436 docstring const xref = data.getXRef();
438 return _("No year"); // no luck
439 BiblioInfo::const_iterator const xrefit = find(xref);
441 return _("No year"); // no luck again
442 BibTeXInfo const & xref_data = xrefit->second;
443 return xref_data.getYear();
444 return data.getYear();
448 docstring const BiblioInfo::getInfo(docstring const & key) const
450 BiblioInfo::const_iterator it = find(key);
453 BibTeXInfo const & data = it->second;
454 BibTeXInfo const * xrefptr = 0;
455 docstring const xref = data.getXRef();
457 BiblioInfo::const_iterator const xrefit = find(xref);
459 xrefptr = &(xrefit->second);
461 return data.getInfo(xrefptr);
465 vector<docstring> const BiblioInfo::getCiteStrings(
466 docstring const & key, Buffer const & buf) const
468 CiteEngine const engine = buf.params().citeEngine();
469 if (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL)
470 return getNumericalStrings(key, buf);
472 return getAuthorYearStrings(key, buf);
476 vector<docstring> const BiblioInfo::getNumericalStrings(
477 docstring const & key, Buffer const & buf) const
480 return vector<docstring>();
482 docstring const author = getAbbreviatedAuthor(key);
483 docstring const year = getYear(key);
484 if (author.empty() || year.empty())
485 return vector<docstring>();
487 vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
489 vector<docstring> vec(styles.size());
490 for (size_t i = 0; i != vec.size(); ++i) {
496 str = from_ascii("[#ID]");
500 str = _("Add to bibliography only.");
504 str = author + " [#ID]";
508 str = author + " #ID";
512 str = from_ascii("#ID");
524 str = '(' + year + ')';
535 vector<docstring> const BiblioInfo::getAuthorYearStrings(
536 docstring const & key, Buffer const & buf) const
539 return vector<docstring>();
541 docstring const author = getAbbreviatedAuthor(key);
542 docstring const year = getYear(key);
543 if (author.empty() || year.empty())
544 return vector<docstring>();
546 vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
548 vector<docstring> vec(styles.size());
549 for (size_t i = 0; i != vec.size(); ++i) {
554 // jurabib only: Author/Annotator
555 // (i.e. the "before" field, 2nd opt arg)
556 str = author + "/<" + _("before") + '>';
560 str = _("Add to bibliography only.");
564 str = author + " (" + year + ')';
568 str = '(' + author + ", " + year + ')';
572 str = author + ' ' + year ;
576 str = author + ", " + year ;
588 str = '(' + year + ')';
597 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
599 bimap_.insert(info.begin(), info.end());
604 // used in xhtml to sort a list of BibTeXInfo objects
605 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
607 return lhs->getAbbreviatedAuthor() < rhs->getAbbreviatedAuthor();
612 void BiblioInfo::collectCitedEntries(Buffer const & buf)
614 cited_entries_.clear();
615 // We are going to collect all the citation keys used in the document,
616 // getting them from the TOC.
617 // FIXME We may want to collect these differently, in the first case,
618 // so that we might have them in order of appearance.
619 set<docstring> citekeys;
620 Toc const & toc = buf.tocBackend().toc("citation");
621 Toc::const_iterator it = toc.begin();
622 Toc::const_iterator const en = toc.end();
623 for (; it != en; ++it) {
624 if (it->str().empty())
626 vector<docstring> const keys = getVectorFromString(it->str());
627 citekeys.insert(keys.begin(), keys.end());
629 if (citekeys.empty())
632 // We have a set of the keys used in this document.
633 // We will now convert it to a list of the BibTeXInfo objects used in
635 vector<BibTeXInfo const *> bi;
636 set<docstring>::const_iterator cit = citekeys.begin();
637 set<docstring>::const_iterator const cen = citekeys.end();
638 for (; cit != cen; ++cit) {
639 BiblioInfo::const_iterator const bt = find(*cit);
640 if (bt == end() || !bt->second.isBibTeX())
642 bi.push_back(&(bt->second));
645 sort(bi.begin(), bi.end(), lSorter);
647 // Now we can write the sorted keys
648 vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
649 vector<BibTeXInfo const *>::const_iterator ben = bi.end();
650 for (; bit != ben; ++bit)
651 cited_entries_.push_back((*bit)->key());
655 void BiblioInfo::makeCitationLabels(Buffer const & buf)
657 collectCitedEntries(buf);
658 // FIXME It'd be nice to do author-year as well as numerical
659 // and maybe even some other sorts of labels.
660 vector<docstring>::const_iterator it = cited_entries_.begin();
661 vector<docstring>::const_iterator const en = cited_entries_.end();
663 for (; it != en; ++it) {
664 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
665 // this shouldn't happen, but...
666 if (biit == bimap_.end())
668 BibTeXInfo & entry = biit->second;
669 docstring const key = convert<docstring>(++keynumber);
670 entry.setCiteKey(key);
675 //////////////////////////////////////////////////////////////////////
679 //////////////////////////////////////////////////////////////////////
684 char const * const citeCommands[] = {
685 "cite", "citet", "citep", "citealt", "citealp",
686 "citeauthor", "citeyear", "citeyearpar", "nocite" };
688 unsigned int const nCiteCommands =
689 sizeof(citeCommands) / sizeof(char *);
691 CiteStyle const citeStylesArray[] = {
692 CITE, CITET, CITEP, CITEALT, CITEALP,
693 CITEAUTHOR, CITEYEAR, CITEYEARPAR, NOCITE };
695 unsigned int const nCiteStyles =
696 sizeof(citeStylesArray) / sizeof(CiteStyle);
698 CiteStyle const citeStylesFull[] = {
699 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
701 unsigned int const nCiteStylesFull =
702 sizeof(citeStylesFull) / sizeof(CiteStyle);
704 CiteStyle const citeStylesUCase[] = {
705 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
707 unsigned int const nCiteStylesUCase =
708 sizeof(citeStylesUCase) / sizeof(CiteStyle);
713 CitationStyle citationStyleFromString(string const & command)
719 string cmd = command;
721 s.forceUpperCase = true;
725 size_t const n = cmd.size() - 1;
726 if (cmd != "cite" && cmd[n] == '*') {
728 cmd = cmd.substr(0, n);
731 char const * const * const last = citeCommands + nCiteCommands;
732 char const * const * const ptr = find(citeCommands, last, cmd);
735 size_t idx = ptr - citeCommands;
736 s.style = citeStylesArray[idx];
742 string citationStyleToString(const CitationStyle & s)
744 string cite = citeCommands[s.style];
746 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
747 if (std::find(citeStylesFull, last, s.style) != last)
751 if (s.forceUpperCase) {
752 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
753 if (std::find(citeStylesUCase, last, s.style) != last)
760 vector<CiteStyle> citeStyles(CiteEngine engine)
762 unsigned int nStyles = 0;
763 unsigned int start = 0;
770 case ENGINE_NATBIB_AUTHORYEAR:
771 case ENGINE_NATBIB_NUMERICAL:
772 nStyles = nCiteStyles - 1;
776 nStyles = nCiteStyles;
781 vector<CiteStyle> styles(nStyles);
784 for (; i != styles.size(); ++i, ++j)
785 styles[i] = citeStylesArray[j];