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 bool BibTeXInfo::hasField(docstring const & field) const
213 return count(field) == 1;
217 docstring const BibTeXInfo::getAbbreviatedAuthor() const
220 docstring const opt = label();
225 split(opt, authors, '(');
229 docstring author = convertLaTeXCommands(operator[]("author"));
230 if (author.empty()) {
231 author = convertLaTeXCommands(operator[]("editor"));
236 // OK, we've got some names. Let's format them.
237 // Try to split the author list on " and "
238 vector<docstring> const authors =
239 getVectorFromString(author, from_ascii(" and "));
241 if (authors.size() == 2)
242 return bformat(_("%1$s and %2$s"),
243 familyName(authors[0]), familyName(authors[1]));
245 if (authors.size() > 2)
246 return bformat(_("%1$s et al."), familyName(authors[0]));
248 return familyName(authors[0]);
252 docstring const BibTeXInfo::getYear() const
255 return operator[]("year");
257 docstring const opt = label();
262 docstring const tmp = split(opt, authors, '(');
264 split(tmp, year, ')');
269 docstring const BibTeXInfo::getXRef() const
273 return operator[]("crossref");
277 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref) const
283 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
289 // This could be made a lot better using the entry_type_
290 // field to customize the output based upon entry type.
292 // Search for all possible "required" fields
293 docstring author = getValueForKey("author", xref);
295 author = getValueForKey("editor", xref);
297 docstring year = getValueForKey("year", xref);
298 docstring title = getValueForKey("title", xref);
299 docstring docLoc = getValueForKey("pages", xref);
300 if (docLoc.empty()) {
301 docLoc = getValueForKey("chapter", xref);
303 docLoc = _("Ch. ") + docLoc;
305 docLoc = _("pp. ") + docLoc;
308 docstring media = getValueForKey("journal", xref);
310 media = getValueForKey("publisher", xref);
312 media = getValueForKey("school", xref);
314 media = getValueForKey("institution");
317 docstring volume = getValueForKey("volume", xref);
319 odocstringstream result;
321 result << author << ", ";
325 result << ", " << media;
327 result << " (" << year << ")";
329 result << ", " << docLoc;
331 docstring const result_str = rtrim(result.str());
332 if (!result_str.empty()) {
333 info_ = convertLaTeXCommands(result_str);
337 // This should never happen (or at least be very unusual!)
338 static docstring e = docstring();
343 docstring const & BibTeXInfo::operator[](docstring const & field) const
345 BibTeXInfo::const_iterator it = find(field);
348 static docstring const empty_value = docstring();
353 docstring const & BibTeXInfo::operator[](string const & field) const
355 return operator[](from_ascii(field));
359 docstring BibTeXInfo::getValueForKey(string const & key,
360 BibTeXInfo const * const xref) const
362 docstring const ret = operator[](key);
363 if (!ret.empty() || !xref)
369 //////////////////////////////////////////////////////////////////////
373 //////////////////////////////////////////////////////////////////////
376 // A functor for use with sort, leading to case insensitive sorting
377 class compareNoCase: public binary_function<docstring, docstring, bool>
380 bool operator()(docstring const & s1, docstring const & s2) const {
381 return compare_no_case(s1, s2) < 0;
387 vector<docstring> const BiblioInfo::getKeys() const
389 vector<docstring> bibkeys;
390 BiblioInfo::const_iterator it = begin();
391 for (; it != end(); ++it)
392 bibkeys.push_back(it->first);
393 sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
398 vector<docstring> const BiblioInfo::getFields() const
400 vector<docstring> bibfields;
401 set<docstring>::const_iterator it = field_names_.begin();
402 set<docstring>::const_iterator end = field_names_.end();
403 for (; it != end; ++it)
404 bibfields.push_back(*it);
405 sort(bibfields.begin(), bibfields.end());
410 vector<docstring> const BiblioInfo::getEntries() const
412 vector<docstring> bibentries;
413 set<docstring>::const_iterator it = entry_types_.begin();
414 set<docstring>::const_iterator end = entry_types_.end();
415 for (; it != end; ++it)
416 bibentries.push_back(*it);
417 sort(bibentries.begin(), bibentries.end());
422 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
424 BiblioInfo::const_iterator it = find(key);
427 BibTeXInfo const & data = it->second;
428 return data.getAbbreviatedAuthor();
432 docstring const BiblioInfo::getYear(docstring const & key) const
434 BiblioInfo::const_iterator it = find(key);
437 BibTeXInfo const & data = it->second;
438 docstring year = data.getYear();
441 // let's try the crossref
442 docstring const xref = data.getXRef();
444 return _("No year"); // no luck
445 BiblioInfo::const_iterator const xrefit = find(xref);
447 return _("No year"); // no luck again
448 BibTeXInfo const & xref_data = xrefit->second;
449 return xref_data.getYear();
450 return data.getYear();
454 docstring const BiblioInfo::getInfo(docstring const & key) const
456 BiblioInfo::const_iterator it = find(key);
459 BibTeXInfo const & data = it->second;
460 BibTeXInfo const * xrefptr = 0;
461 docstring const xref = data.getXRef();
463 BiblioInfo::const_iterator const xrefit = find(xref);
465 xrefptr = &(xrefit->second);
467 return data.getInfo(xrefptr);
471 vector<docstring> const BiblioInfo::getCiteStrings(
472 docstring const & key, Buffer const & buf) const
474 CiteEngine const engine = buf.params().citeEngine();
475 if (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL)
476 return getNumericalStrings(key, buf);
478 return getAuthorYearStrings(key, buf);
482 vector<docstring> const BiblioInfo::getNumericalStrings(
483 docstring const & key, Buffer const & buf) const
486 return vector<docstring>();
488 docstring const author = getAbbreviatedAuthor(key);
489 docstring const year = getYear(key);
490 if (author.empty() || year.empty())
491 return vector<docstring>();
493 vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
495 vector<docstring> vec(styles.size());
496 for (size_t i = 0; i != vec.size(); ++i) {
502 str = from_ascii("[#ID]");
506 str = _("Add to bibliography only.");
510 str = author + " [#ID]";
514 str = author + " #ID";
518 str = from_ascii("#ID");
530 str = '(' + year + ')';
541 vector<docstring> const BiblioInfo::getAuthorYearStrings(
542 docstring const & key, Buffer const & buf) const
545 return vector<docstring>();
547 docstring const author = getAbbreviatedAuthor(key);
548 docstring const year = getYear(key);
549 if (author.empty() || year.empty())
550 return vector<docstring>();
552 vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
554 vector<docstring> vec(styles.size());
555 for (size_t i = 0; i != vec.size(); ++i) {
560 // jurabib only: Author/Annotator
561 // (i.e. the "before" field, 2nd opt arg)
562 str = author + "/<" + _("before") + '>';
566 str = _("Add to bibliography only.");
570 str = author + " (" + year + ')';
574 str = '(' + author + ", " + year + ')';
578 str = author + ' ' + year ;
582 str = author + ", " + year ;
594 str = '(' + year + ')';
603 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
605 bimap_.insert(info.begin(), info.end());
610 // used in xhtml to sort a list of BibTeXInfo objects
611 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
613 return lhs->getAbbreviatedAuthor() < rhs->getAbbreviatedAuthor();
618 void BiblioInfo::collectCitedEntries(Buffer const & buf)
620 cited_entries_.clear();
621 // We are going to collect all the citation keys used in the document,
622 // getting them from the TOC.
623 // FIXME We may want to collect these differently, in the first case,
624 // so that we might have them in order of appearance.
625 set<docstring> citekeys;
626 Toc const & toc = buf.tocBackend().toc("citation");
627 Toc::const_iterator it = toc.begin();
628 Toc::const_iterator const en = toc.end();
629 for (; it != en; ++it) {
630 if (it->str().empty())
632 vector<docstring> const keys = getVectorFromString(it->str());
633 citekeys.insert(keys.begin(), keys.end());
635 if (citekeys.empty())
638 // We have a set of the keys used in this document.
639 // We will now convert it to a list of the BibTeXInfo objects used in
641 vector<BibTeXInfo const *> bi;
642 set<docstring>::const_iterator cit = citekeys.begin();
643 set<docstring>::const_iterator const cen = citekeys.end();
644 for (; cit != cen; ++cit) {
645 BiblioInfo::const_iterator const bt = find(*cit);
646 if (bt == end() || !bt->second.isBibTeX())
648 bi.push_back(&(bt->second));
651 sort(bi.begin(), bi.end(), lSorter);
653 // Now we can write the sorted keys
654 vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
655 vector<BibTeXInfo const *>::const_iterator ben = bi.end();
656 for (; bit != ben; ++bit)
657 cited_entries_.push_back((*bit)->key());
661 void BiblioInfo::makeCitationLabels(Buffer const & buf)
663 collectCitedEntries(buf);
664 // FIXME It'd be nice to do author-year as well as numerical
665 // and maybe even some other sorts of labels.
666 vector<docstring>::const_iterator it = cited_entries_.begin();
667 vector<docstring>::const_iterator const en = cited_entries_.end();
669 for (; it != en; ++it) {
670 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
671 // this shouldn't happen, but...
672 if (biit == bimap_.end())
674 BibTeXInfo & entry = biit->second;
675 docstring const key = convert<docstring>(++keynumber);
676 entry.setCiteKey(key);
681 //////////////////////////////////////////////////////////////////////
685 //////////////////////////////////////////////////////////////////////
690 char const * const citeCommands[] = {
691 "cite", "citet", "citep", "citealt", "citealp",
692 "citeauthor", "citeyear", "citeyearpar", "nocite" };
694 unsigned int const nCiteCommands =
695 sizeof(citeCommands) / sizeof(char *);
697 CiteStyle const citeStylesArray[] = {
698 CITE, CITET, CITEP, CITEALT, CITEALP,
699 CITEAUTHOR, CITEYEAR, CITEYEARPAR, NOCITE };
701 unsigned int const nCiteStyles =
702 sizeof(citeStylesArray) / sizeof(CiteStyle);
704 CiteStyle const citeStylesFull[] = {
705 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
707 unsigned int const nCiteStylesFull =
708 sizeof(citeStylesFull) / sizeof(CiteStyle);
710 CiteStyle const citeStylesUCase[] = {
711 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
713 unsigned int const nCiteStylesUCase =
714 sizeof(citeStylesUCase) / sizeof(CiteStyle);
719 CitationStyle citationStyleFromString(string const & command)
725 string cmd = command;
727 s.forceUpperCase = true;
731 size_t const n = cmd.size() - 1;
732 if (cmd != "cite" && cmd[n] == '*') {
734 cmd = cmd.substr(0, n);
737 char const * const * const last = citeCommands + nCiteCommands;
738 char const * const * const ptr = find(citeCommands, last, cmd);
741 size_t idx = ptr - citeCommands;
742 s.style = citeStylesArray[idx];
748 string citationStyleToString(const CitationStyle & s)
750 string cite = citeCommands[s.style];
752 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
753 if (std::find(citeStylesFull, last, s.style) != last)
757 if (s.forceUpperCase) {
758 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
759 if (std::find(citeStylesUCase, last, s.style) != last)
766 vector<CiteStyle> citeStyles(CiteEngine engine)
768 unsigned int nStyles = 0;
769 unsigned int start = 0;
776 case ENGINE_NATBIB_AUTHORYEAR:
777 case ENGINE_NATBIB_NUMERICAL:
778 nStyles = nCiteStyles - 1;
782 nStyles = nCiteStyles;
787 vector<CiteStyle> styles(nStyles);
790 for (; i != styles.size(); ++i, ++j)
791 styles[i] = citeStylesArray[j];