3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
11 * Full author contact details are available in file CREDITS.
16 #include "BiblioInfo.h"
18 #include "BufferParams.h"
19 #include "buffer_funcs.h"
21 #include "InsetIterator.h"
23 #include "Paragraph.h"
24 #include "TextClass.h"
25 #include "TocBackend.h"
27 #include "support/convert.h"
28 #include "support/debug.h"
29 #include "support/docstream.h"
30 #include "support/gettext.h"
31 #include "support/lassert.h"
32 #include "support/lstrings.h"
33 #include "support/regex.h"
34 #include "support/textutils.h"
39 using namespace lyx::support;
46 // gets the "family name" from an author-type string
47 docstring familyName(docstring const & name)
52 // first we look for a comma, and take the last name to be everything
53 // preceding the right-most one, so that we also get the "jr" part.
54 docstring::size_type idx = name.rfind(',');
55 if (idx != docstring::npos)
56 return ltrim(name.substr(0, idx));
58 // OK, so now we want to look for the last name. We're going to
59 // include the "von" part. This isn't perfect.
60 // Split on spaces, to get various tokens.
61 vector<docstring> pieces = getVectorFromString(name, from_ascii(" "));
62 // If we only get two, assume the last one is the last name
63 if (pieces.size() <= 2)
66 // Now we look for the first token that begins with a lower case letter.
67 vector<docstring>::const_iterator it = pieces.begin();
68 vector<docstring>::const_iterator en = pieces.end();
69 for (; it != en; ++it) {
72 char_type const c = (*it)[0];
77 if (it == en) // we never found a "von"
80 // reconstruct what we need to return
83 for (; it != en; ++it) {
94 // converts a string containing LaTeX commands into unicode
96 docstring convertLaTeXCommands(docstring const & str)
101 bool scanning_cmd = false;
102 bool scanning_math = false;
103 bool escaped = false; // used to catch \$, etc.
104 while (!val.empty()) {
105 char_type const ch = val[0];
107 // if we're scanning math, we output everything until we
108 // find an unescaped $, at which point we break out.
115 scanning_math = false;
121 // if we're scanning a command name, then we just
122 // discard characters until we hit something that
125 if (isAlphaASCII(ch)) {
130 // so we're done with this command.
131 // now we fall through and check this character.
132 scanning_cmd = false;
135 // was the last character a \? If so, then this is something like:
136 // \\ or \$, so we'll just output it. That's probably not always right...
138 // exception: output \, as THIN SPACE
140 ret.push_back(0x2009);
151 scanning_math = true;
155 // we just ignore braces
156 if (ch == '{' || ch == '}') {
161 // we're going to check things that look like commands, so if
162 // this doesn't, just output it.
169 // ok, could be a command of some sort
170 // let's see if it corresponds to some unicode
171 // unicodesymbols has things in the form: \"{u},
172 // whereas we may see things like: \"u. So we'll
173 // look for that and change it, if necessary.
174 // FIXME: This is a sort of mini-tex2lyx.
175 // Use the real tex2lyx instead!
176 static lyx::regex const reg("^\\\\\\W\\w");
177 if (lyx::regex_search(to_utf8(val), reg)) {
178 val.insert(3, from_ascii("}"));
179 val.insert(2, from_ascii("{"));
183 docstring const cnvtd = Encodings::fromLaTeXCommand(val,
184 Encodings::TEXT_CMD, termination, rem);
185 if (!cnvtd.empty()) {
186 // it did, so we'll take that bit and proceed with what's left
191 // it's a command of some sort
200 // Escape '<' and '>' and remove richtext markers (e.g. {!this is richtext!}) from a string.
201 docstring processRichtext(docstring const & str, bool richtext)
206 bool scanning_rich = false;
207 while (!val.empty()) {
208 char_type const ch = val[0];
209 if (ch == '{' && val.size() > 1 && val[1] == '!') {
210 // beginning of rich text
211 scanning_rich = true;
215 if (scanning_rich && ch == '!' && val.size() > 1 && val[1] == '}') {
217 scanning_rich = false;
225 // we need to escape '<' and '>'
233 } else if (!scanning_rich /* && !richtext */)
235 // else the character is discarded, which will happen only if
236 // richtext == false and we are scanning rich text
245 //////////////////////////////////////////////////////////////////////
249 //////////////////////////////////////////////////////////////////////
251 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
252 : is_bibtex_(true), bib_key_(key), entry_type_(type), info_(),
257 docstring const BibTeXInfo::getAbbreviatedAuthor(bool jurabib_style, string lang) const
260 docstring const opt = label();
265 docstring const remainder = trim(split(opt, authors, '('));
266 if (remainder.empty())
267 // in this case, we didn't find a "(",
268 // so we don't have author (year)
273 docstring author = convertLaTeXCommands(operator[]("author"));
274 if (author.empty()) {
275 author = convertLaTeXCommands(operator[]("editor"));
280 // FIXME Move this to a separate routine that can
281 // be called from elsewhere.
283 // OK, we've got some names. Let's format them.
284 // Try to split the author list on " and "
285 vector<docstring> const authors =
286 getVectorFromString(author, from_ascii(" and "));
288 if (jurabib_style && (authors.size() == 2 || authors.size() == 3)) {
289 docstring shortauthor = familyName(authors[0])
290 + "/" + familyName(authors[1]);
291 if (authors.size() == 3)
292 shortauthor += "/" + familyName(authors[2]);
296 if (authors.size() == 2)
297 return bformat(translateIfPossible(from_ascii("%1$s and %2$s"), lang),
298 familyName(authors[0]), familyName(authors[1]));
300 if (authors.size() > 2)
301 return bformat(translateIfPossible(from_ascii("%1$s et al."), lang),
302 familyName(authors[0]));
304 return familyName(authors[0]);
308 docstring const BibTeXInfo::getYear() const
311 return operator[]("year");
313 docstring const opt = label();
318 docstring tmp = split(opt, authors, '(');
320 // we don't have author (year)
323 tmp = split(tmp, year, ')');
328 docstring const BibTeXInfo::getXRef() const
332 return operator[]("crossref");
338 string parseOptions(string const & format, string & optkey,
339 string & ifpart, string & elsepart);
341 // Calls parseOptions to deal with an embedded option, such as:
342 // {%number%[[, no.~%number%]]}
343 // which must appear at the start of format. ifelsepart gets the
344 // whole of the option, and we return what's left after the option.
345 // we return format if there is an error.
346 string parseEmbeddedOption(string const & format, string & ifelsepart)
348 LASSERT(format[0] == '{' && format[1] == '%', return format);
352 string const rest = parseOptions(format, optkey, ifpart, elsepart);
353 if (format == rest) { // parse error
354 LYXERR0("ERROR! Couldn't parse `" << format <<"'.");
357 LASSERT(rest.size() <= format.size(), /* */);
358 ifelsepart = format.substr(0, format.size() - rest.size());
363 // Gets a "clause" from a format string, where the clause is
364 // delimited by '[[' and ']]'. Returns what is left after the
365 // clause is removed, and returns format if there is an error.
366 string getClause(string const & format, string & clause)
371 // we'll remove characters from the front of fmt as we
373 while (!fmt.empty()) {
374 if (fmt[0] == ']' && fmt.size() > 1 && fmt[1] == ']') {
379 // check for an embedded option
380 if (fmt[0] == '{' && fmt.size() > 1 && fmt[1] == '%') {
382 string const rest = parseEmbeddedOption(fmt, part);
384 LYXERR0("ERROR! Couldn't parse embedded option in `" << format <<"'.");
389 } else { // it's just a normal character
398 // parse an options string, which must appear at the start of the
399 // format parameter. puts the parsed bits in optkey, ifpart, and
400 // elsepart and returns what's left after the option is removed.
401 // if there's an error, it returns format itself.
402 string parseOptions(string const & format, string & optkey,
403 string & ifpart, string & elsepart)
405 LASSERT(format[0] == '{' && format[1] == '%', return format);
407 string fmt = format.substr(2);
408 size_t pos = fmt.find('%'); // end of key
409 if (pos == string::npos) {
410 LYXERR0("Error parsing `" << format <<"'. Can't find end of key.");
413 optkey = fmt.substr(0,pos);
414 fmt = fmt.substr(pos + 1);
415 // [[format]] should be next
416 if (fmt[0] != '[' || fmt[1] != '[') {
417 LYXERR0("Error parsing `" << format <<"'. Can't find '[[' after key.");
422 fmt = getClause(curfmt, ifpart);
424 LYXERR0("Error parsing `" << format <<"'. Couldn't get if clause.");
428 if (fmt[0] == '}') // we're done, no else clause
429 return fmt.substr(1);
431 // else part should follow
432 if (fmt[0] != '[' || fmt[1] != '[') {
433 LYXERR0("Error parsing `" << format <<"'. Can't find else clause.");
438 fmt = getClause(curfmt, elsepart);
440 if (fmt == curfmt || fmt[0] != '}') {
441 LYXERR0("Error parsing `" << format <<"'. Can't find end of option.");
444 return fmt.substr(1);
451 docstring BibTeXInfo::expandFormat(string const & format,
452 BibTeXInfo const * const xref, int & counter, Buffer const & buf,
453 docstring before, docstring after, docstring dialog, bool next) const
455 // incorrect use of macros could put us in an infinite loop
456 static int max_passes = 5000;
457 docstring ret; // return value
459 string lang = buf.params().language->code();
460 bool scanning_key = false;
461 bool scanning_rich = false;
463 CiteEngineType const engine_type = buf.params().citeEngineType();
465 // we'll remove characters from the front of fmt as we
467 while (!fmt.empty()) {
468 if (counter++ > max_passes) {
469 LYXERR0("Recursion limit reached while parsing `"
474 char_type thischar = fmt[0];
475 if (thischar == '%') {
476 // beginning or end of key
479 scanning_key = false;
480 // so we replace the key with its value, which may be empty
483 // FIXME: instead of passing the buf, just past the macros
484 // FIXME: and the language code
486 buf.params().documentClass().getCiteMacro(engine_type, key);
487 fmt = val + fmt.substr(1);
489 } else if (key[0] == '_') {
490 // a translatable bit
492 buf.params().documentClass().getCiteMacro(engine_type, key);
493 docstring const trans =
494 translateIfPossible(from_utf8(val), lang);
497 docstring const val =
498 getValueForKey(key, before, after, dialog, xref, lang);
507 else if (thischar == '{') {
508 // beginning of option?
510 LYXERR0("ERROR: Found `{' when scanning key in `" << format << "'.");
513 if (fmt.size() > 1) {
515 // it is the beginning of an optional format
519 string const newfmt =
520 parseOptions(fmt, optkey, ifpart, elsepart);
521 if (newfmt == fmt) // parse error
524 docstring const val =
525 getValueForKey(optkey, before, after, dialog, xref, lang);
526 if (optkey == "next" && next)
527 ret += from_utf8(ifpart); // without expansion
528 else if (!val.empty())
529 ret += expandFormat(ifpart, xref, counter, buf,
530 before, after, dialog, next);
531 else if (!elsepart.empty())
532 ret += expandFormat(elsepart, xref, counter, buf,
533 before, after, dialog, next);
534 // fmt will have been shortened for us already
538 // beginning of rich text
539 scanning_rich = true;
541 ret += from_ascii("{!");
545 // we are here if '{' was not followed by % or !.
546 // So it's just a character.
549 else if (scanning_rich && thischar == '!'
550 && fmt.size() > 1 && fmt[1] == '}') {
552 scanning_rich = false;
554 ret += from_ascii("!}");
557 else if (scanning_key)
558 key += char(thischar);
564 LYXERR0("Never found end of key in `" << format << "'!");
568 LYXERR0("Never found end of rich text in `" << format << "'!");
575 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref,
576 Buffer const & buf, bool richtext) const
582 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
587 CiteEngineType const engine_type = buf.params().citeEngineType();
588 DocumentClass const & dc = buf.params().documentClass();
589 string const & format = dc.getCiteFormat(engine_type, to_utf8(entry_type_));
591 info_ = expandFormat(format, xref, counter, buf,
592 docstring(), docstring(), docstring(), false);
595 info_ = convertLaTeXCommands(info_);
600 docstring const BibTeXInfo::getLabel(BibTeXInfo const * const xref,
601 Buffer const & buf, string const & format, bool richtext,
602 docstring before, docstring after, docstring dialog, bool next) const
608 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
615 loclabel = expandFormat(format, xref, counter, buf,
616 before, after, dialog, next);
618 if (!loclabel.empty() && !next) {
619 loclabel = processRichtext(loclabel, richtext);
620 loclabel = convertLaTeXCommands(loclabel);
626 docstring const & BibTeXInfo::operator[](docstring const & field) const
628 BibTeXInfo::const_iterator it = find(field);
631 static docstring const empty_value = docstring();
636 docstring const & BibTeXInfo::operator[](string const & field) const
638 return operator[](from_ascii(field));
642 docstring BibTeXInfo::getValueForKey(string const & key,
643 docstring const & before, docstring const & after, docstring const & dialog,
644 BibTeXInfo const * const xref, string lang) const
646 docstring ret = operator[](key);
647 if (ret.empty() && xref)
652 // FIXME: dialog, textbefore and textafter have nothing to do with this
655 else if (key == "entrytype")
657 else if (key == "key")
659 else if (key == "label")
661 else if (key == "abbrvauthor")
662 // Special key to provide abbreviated author names.
663 return getAbbreviatedAuthor(false, lang);
664 else if (key == "shortauthor")
665 // When shortauthor is not defined, jurabib automatically
666 // provides jurabib-style abbreviated author names. We do
668 return getAbbreviatedAuthor(true, lang);
669 else if (key == "shorttitle") {
670 // When shorttitle is not defined, jurabib uses for `article'
671 // and `periodical' entries the form `journal volume [year]'
672 // and for other types of entries it uses the `title' field.
673 if (entry_type_ == "article" || entry_type_ == "periodical")
674 return operator[]("journal") + " " + operator[]("volume")
675 + " [" + operator[]("year") + "]";
677 return operator[]("title");
678 } else if (key == "textbefore")
680 else if (key == "textafter")
682 else if (key == "year")
688 //////////////////////////////////////////////////////////////////////
692 //////////////////////////////////////////////////////////////////////
696 // A functor for use with sort, leading to case insensitive sorting
697 class compareNoCase: public binary_function<docstring, docstring, bool>
700 bool operator()(docstring const & s1, docstring const & s2) const {
701 return compare_no_case(s1, s2) < 0;
708 vector<docstring> const BiblioInfo::getKeys() const
710 vector<docstring> bibkeys;
711 BiblioInfo::const_iterator it = begin();
712 for (; it != end(); ++it)
713 bibkeys.push_back(it->first);
714 sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
719 vector<docstring> const BiblioInfo::getFields() const
721 vector<docstring> bibfields;
722 set<docstring>::const_iterator it = field_names_.begin();
723 set<docstring>::const_iterator end = field_names_.end();
724 for (; it != end; ++it)
725 bibfields.push_back(*it);
726 sort(bibfields.begin(), bibfields.end());
731 vector<docstring> const BiblioInfo::getEntries() const
733 vector<docstring> bibentries;
734 set<docstring>::const_iterator it = entry_types_.begin();
735 set<docstring>::const_iterator end = entry_types_.end();
736 for (; it != end; ++it)
737 bibentries.push_back(*it);
738 sort(bibentries.begin(), bibentries.end());
743 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key, string lang) const
745 BiblioInfo::const_iterator it = find(key);
748 BibTeXInfo const & data = it->second;
749 return data.getAbbreviatedAuthor(false, lang);
753 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
755 BiblioInfo::const_iterator it = find(key);
758 BibTeXInfo const & data = it->second;
759 return data.citeNumber();
763 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier, string lang) const
765 BiblioInfo::const_iterator it = find(key);
768 BibTeXInfo const & data = it->second;
769 docstring year = data.getYear();
771 // let's try the crossref
772 docstring const xref = data.getXRef();
775 return translateIfPossible(from_ascii("No year"), lang);
776 BiblioInfo::const_iterator const xrefit = find(xref);
779 return translateIfPossible(from_ascii("No year"), lang);
780 BibTeXInfo const & xref_data = xrefit->second;
781 year = xref_data.getYear();
783 if (use_modifier && data.modifier() != 0)
784 year += data.modifier();
789 docstring const BiblioInfo::getInfo(docstring const & key,
790 Buffer const & buf, bool richtext) const
792 BiblioInfo::const_iterator it = find(key);
794 return docstring(_("Bibliography entry not found!"));
795 BibTeXInfo const & data = it->second;
796 BibTeXInfo const * xrefptr = 0;
797 docstring const xref = data.getXRef();
799 BiblioInfo::const_iterator const xrefit = find(xref);
801 xrefptr = &(xrefit->second);
803 return data.getInfo(xrefptr, buf, richtext);
807 docstring const BiblioInfo::getLabel(vector<docstring> const & keys,
808 Buffer const & buf, string const & style, bool richtext,
809 docstring const & before, docstring const & after, docstring const & dialog) const
811 CiteEngineType const engine_type = buf.params().citeEngineType();
812 DocumentClass const & dc = buf.params().documentClass();
813 string const & format = dc.getCiteFormat(engine_type, style, "cite");
814 docstring ret = from_utf8(format);
815 vector<docstring>::const_iterator key = keys.begin();
816 vector<docstring>::const_iterator ken = keys.end();
817 for (; key != ken; ++key) {
818 BiblioInfo::const_iterator it = find(*key);
819 BibTeXInfo empty_data;
820 empty_data.key(*key);
821 BibTeXInfo & data = empty_data;
822 BibTeXInfo const * xrefptr = 0;
825 docstring const xref = data.getXRef();
827 BiblioInfo::const_iterator const xrefit = find(xref);
829 xrefptr = &(xrefit->second);
832 ret = data.getLabel(xrefptr, buf, to_utf8(ret), richtext,
833 before, after, dialog, key+1 != ken);
839 bool BiblioInfo::isBibtex(docstring const & key) const
841 BiblioInfo::const_iterator it = find(key);
844 return it->second.isBibTeX();
848 vector<docstring> const BiblioInfo::getCiteStrings(
849 vector<docstring> const & keys, vector<CitationStyle> const & styles,
850 Buffer const & buf, bool richtext, docstring const & before,
851 docstring const & after, docstring const & dialog) const
854 return vector<docstring>();
857 vector<docstring> vec(styles.size());
858 for (size_t i = 0; i != vec.size(); ++i) {
859 style = styles[i].cmd;
860 vec[i] = getLabel(keys, buf, style, richtext, before, after, dialog);
867 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
869 bimap_.insert(info.begin(), info.end());
870 field_names_.insert(info.field_names_.begin(), info.field_names_.end());
871 entry_types_.insert(info.entry_types_.begin(), info.entry_types_.end());
877 // used in xhtml to sort a list of BibTeXInfo objects
878 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
880 docstring const lauth = lhs->getAbbreviatedAuthor();
881 docstring const rauth = rhs->getAbbreviatedAuthor();
882 docstring const lyear = lhs->getYear();
883 docstring const ryear = rhs->getYear();
884 docstring const ltitl = lhs->operator[]("title");
885 docstring const rtitl = rhs->operator[]("title");
886 return (lauth < rauth)
887 || (lauth == rauth && lyear < ryear)
888 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
894 void BiblioInfo::collectCitedEntries(Buffer const & buf)
896 cited_entries_.clear();
897 // We are going to collect all the citation keys used in the document,
898 // getting them from the TOC.
899 // FIXME We may want to collect these differently, in the first case,
900 // so that we might have them in order of appearance.
901 set<docstring> citekeys;
902 Toc const & toc = buf.tocBackend().toc("citation");
903 Toc::const_iterator it = toc.begin();
904 Toc::const_iterator const en = toc.end();
905 for (; it != en; ++it) {
906 if (it->str().empty())
908 vector<docstring> const keys = getVectorFromString(it->str());
909 citekeys.insert(keys.begin(), keys.end());
911 if (citekeys.empty())
914 // We have a set of the keys used in this document.
915 // We will now convert it to a list of the BibTeXInfo objects used in
917 vector<BibTeXInfo const *> bi;
918 set<docstring>::const_iterator cit = citekeys.begin();
919 set<docstring>::const_iterator const cen = citekeys.end();
920 for (; cit != cen; ++cit) {
921 BiblioInfo::const_iterator const bt = find(*cit);
922 if (bt == end() || !bt->second.isBibTeX())
924 bi.push_back(&(bt->second));
927 sort(bi.begin(), bi.end(), lSorter);
929 // Now we can write the sorted keys
930 vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
931 vector<BibTeXInfo const *>::const_iterator ben = bi.end();
932 for (; bit != ben; ++bit)
933 cited_entries_.push_back((*bit)->key());
937 void BiblioInfo::makeCitationLabels(Buffer const & buf)
939 collectCitedEntries(buf);
940 CiteEngineType const engine_type = buf.params().citeEngineType();
941 bool const numbers = (engine_type == ENGINE_TYPE_NUMERICAL);
945 // used to remember the last one we saw
946 // we'll be comparing entries to see if we need to add
947 // modifiers, like "1984a"
948 map<docstring, BibTeXInfo>::iterator last;
950 vector<docstring>::const_iterator it = cited_entries_.begin();
951 vector<docstring>::const_iterator const en = cited_entries_.end();
952 for (; it != en; ++it) {
953 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
954 // this shouldn't happen, but...
955 if (biit == bimap_.end())
956 // ...fail gracefully, anyway.
958 BibTeXInfo & entry = biit->second;
960 docstring const num = convert<docstring>(++keynumber);
961 entry.setCiteNumber(num);
963 if (it != cited_entries_.begin()
964 && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
965 // we access the year via getYear() so as to get it from the xref,
966 // if we need to do so
967 && getYear(entry.key()) == getYear(last->second.key())) {
969 // so the last one should have been 'a'
970 last->second.setModifier('a');
972 } else if (modifier == 'z')
979 entry.setModifier(modifier);
980 // remember the last one
987 //////////////////////////////////////////////////////////////////////
991 //////////////////////////////////////////////////////////////////////
994 CitationStyle citationStyleFromString(string const & command)
1000 string cmd = command;
1001 if (cmd[0] == 'C') {
1002 cs.forceUpperCase = true;
1006 size_t const n = cmd.size() - 1;
1007 if (cmd[n] == '*') {
1008 cs.fullAuthorList = true;
1009 cmd = cmd.substr(0, n);
1017 string citationStyleToString(const CitationStyle & cs)
1019 string cmd = cs.cmd;
1020 if (cs.forceUpperCase)
1022 if (cs.fullAuthorList)