]> git.lyx.org Git - lyx.git/blob - src/BiblioInfo.cpp
a2989995d2da5a6b82df59eb09ec47c3045065ea
[lyx.git] / src / BiblioInfo.cpp
1 /**
2  * \file BiblioInfo.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  * \author Herbert Voß
8  * \author Richard Heck
9  * \author Julien Rioux
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "BiblioInfo.h"
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "buffer_funcs.h"
20 #include "Encoding.h"
21 #include "InsetIterator.h"
22 #include "Language.h"
23 #include "Paragraph.h"
24 #include "TextClass.h"
25 #include "TocBackend.h"
26
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"
35
36 #include <set>
37
38 using namespace std;
39 using namespace lyx::support;
40
41
42 namespace lyx {
43
44 namespace {
45
46 // gets the "family name" from an author-type string
47 docstring familyName(docstring const & name)
48 {
49         if (name.empty())
50                 return docstring();
51
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));
57
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)
64                 return pieces.back();
65
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) {
70                 if ((*it).empty())
71                         continue;
72                 char_type const c = (*it)[0];
73                 if (isLower(c))
74                         break;
75         }
76
77         if (it == en) // we never found a "von"
78                 return pieces.back();
79
80         // reconstruct what we need to return
81         docstring retval;
82         bool first = true;
83         for (; it != en; ++it) {
84                 if (!first)
85                         retval += " ";
86                 else
87                         first = false;
88                 retval += *it;
89         }
90         return retval;
91 }
92
93
94 // converts a string containing LaTeX commands into unicode
95 // for display.
96 docstring convertLaTeXCommands(docstring const & str)
97 {
98         docstring val = str;
99         docstring ret;
100
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];
106
107                 // if we're scanning math, we output everything until we
108                 // find an unescaped $, at which point we break out.
109                 if (scanning_math) {
110                         if (escaped)
111                                 escaped = false;
112                         else if (ch == '\\')
113                                 escaped = true;
114                         else if (ch == '$')
115                                 scanning_math = false;
116                         ret += ch;
117                         val = val.substr(1);
118                         continue;
119                 }
120
121                 // if we're scanning a command name, then we just
122                 // discard characters until we hit something that
123                 // isn't alpha.
124                 if (scanning_cmd) {
125                         if (isAlphaASCII(ch)) {
126                                 val = val.substr(1);
127                                 escaped = false;
128                                 continue;
129                         }
130                         // so we're done with this command.
131                         // now we fall through and check this character.
132                         scanning_cmd = false;
133                 }
134
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...
137                 if (escaped) {
138                         // exception: output \, as THIN SPACE
139                         if (ch == ',')
140                                 ret.push_back(0x2009);
141                         else
142                                 ret += ch;
143                         val = val.substr(1);
144                         escaped = false;
145                         continue;
146                 }
147
148                 if (ch == '$') {
149                         ret += ch;
150                         val = val.substr(1);
151                         scanning_math = true;
152                         continue;
153                 }
154
155                 // we just ignore braces
156                 if (ch == '{' || ch == '}') {
157                         val = val.substr(1);
158                         continue;
159                 }
160
161                 // we're going to check things that look like commands, so if
162                 // this doesn't, just output it.
163                 if (ch != '\\') {
164                         ret += ch;
165                         val = val.substr(1);
166                         continue;
167                 }
168
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("{"));
180                 }
181                 bool termination;
182                 docstring rem;
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
187                         ret += cnvtd;
188                         val = rem;
189                         continue;
190                 }
191                 // it's a command of some sort
192                 scanning_cmd = true;
193                 escaped = true;
194                 val = val.substr(1);
195         }
196         return ret;
197 }
198
199
200 // Escape '<' and '>' and remove richtext markers (e.g. {!this is richtext!}) from a string.
201 docstring processRichtext(docstring const & str, bool richtext)
202 {
203         docstring val = str;
204         docstring ret;
205
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;
212                         val = val.substr(2);
213                         continue;
214                 }
215                 if (scanning_rich && ch == '!' && val.size() > 1 && val[1] == '}') {
216                         // end of rich text
217                         scanning_rich = false;
218                         val = val.substr(2);
219                         continue;
220                 }
221                 if (richtext) {
222                         if (scanning_rich)
223                                 ret += ch;
224                         else {
225                                 // we need to escape '<' and '>'
226                                 if (ch == '<')
227                                         ret += "&lt;";
228                                 else if (ch == '>')
229                                         ret += "&gt;";
230                                 else
231                                         ret += ch;
232                         }
233                 } else if (!scanning_rich /* && !richtext */)
234                         ret += ch;
235                 // else the character is discarded, which will happen only if
236                 // richtext == false and we are scanning rich text
237                 val = val.substr(1);
238         }
239         return ret;
240 }
241
242 } // anon namespace
243
244
245 //////////////////////////////////////////////////////////////////////
246 //
247 // BibTeXInfo
248 //
249 //////////////////////////////////////////////////////////////////////
250
251 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
252         : is_bibtex_(true), bib_key_(key), entry_type_(type), info_(),
253           modifier_(0)
254 {}
255
256
257 docstring const BibTeXInfo::getAbbreviatedAuthor(bool jurabib_style, string lang) const
258 {
259         if (!is_bibtex_) {
260                 docstring const opt = label();
261                 if (opt.empty())
262                         return docstring();
263
264                 docstring authors;
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)
269                         return docstring();
270                 return authors;
271         }
272
273         docstring author = convertLaTeXCommands(operator[]("author"));
274         if (author.empty()) {
275                 author = convertLaTeXCommands(operator[]("editor"));
276                 if (author.empty())
277                         return author;
278         }
279
280         // FIXME Move this to a separate routine that can
281         // be called from elsewhere.
282         //
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 "));
287
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]);
293                 return shortauthor;
294         }
295
296         if (authors.size() == 2)
297                 return bformat(translateIfPossible(from_ascii("%1$s and %2$s"), lang),
298                         familyName(authors[0]), familyName(authors[1]));
299
300         if (authors.size() > 2)
301                 return bformat(translateIfPossible(from_ascii("%1$s et al."), lang),
302                         familyName(authors[0]));
303
304         return familyName(authors[0]);
305 }
306
307
308 docstring const BibTeXInfo::getYear() const
309 {
310         if (is_bibtex_)
311                 return operator[]("year");
312
313         docstring const opt = label();
314         if (opt.empty())
315                 return docstring();
316
317         docstring authors;
318         docstring tmp = split(opt, authors, '(');
319         if (tmp.empty())
320                 // we don't have author (year)
321                 return docstring();
322         docstring year;
323         tmp = split(tmp, year, ')');
324         return year;
325 }
326
327
328 docstring const BibTeXInfo::getXRef() const
329 {
330         if (!is_bibtex_)
331                 return docstring();
332         return operator[]("crossref");
333 }
334
335
336 namespace {
337
338 string parseOptions(string const & format, string & optkey,
339                     string & ifpart, string & elsepart);
340
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)
347 {
348         LASSERT(format[0] == '{' && format[1] == '%', return format);
349         string optkey;
350         string ifpart;
351         string elsepart;
352         string const rest = parseOptions(format, optkey, ifpart, elsepart);
353         if (format == rest) { // parse error
354                 LYXERR0("ERROR! Couldn't parse `" << format <<"'.");
355                 return format;
356         }
357         LASSERT(rest.size() <= format.size(), /* */);
358         ifelsepart = format.substr(0, format.size() - rest.size());
359                 return rest;
360 }
361
362
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)
367 {
368         string fmt = format;
369         // remove '[['
370         fmt = fmt.substr(2);
371         // we'll remove characters from the front of fmt as we
372         // deal with them
373         while (!fmt.empty()) {
374                 if (fmt[0] == ']' && fmt.size() > 1 && fmt[1] == ']') {
375                         // that's the end
376                         fmt = fmt.substr(2);
377                         break;
378                 }
379                 // check for an embedded option
380                 if (fmt[0] == '{' && fmt.size() > 1 && fmt[1] == '%') {
381                         string part;
382                         string const rest = parseEmbeddedOption(fmt, part);
383                         if (fmt == rest) {
384                                 LYXERR0("ERROR! Couldn't parse embedded option in `" << format <<"'.");
385                                 return format;
386                         }
387                         clause += part;
388                         fmt = rest;
389                 } else { // it's just a normal character
390                                 clause += fmt[0];
391                                 fmt = fmt.substr(1);
392                 }
393         }
394         return fmt;
395 }
396
397
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)
404 {
405         LASSERT(format[0] == '{' && format[1] == '%', return format);
406         // strip '{%'
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.");
411                 return format;
412         }
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.");
418                 return format;
419         }
420
421         string curfmt = fmt;
422         fmt = getClause(curfmt, ifpart);
423         if (fmt == curfmt) {
424                 LYXERR0("Error parsing  `" << format <<"'. Couldn't get if clause.");
425                 return format;
426         }
427
428         if (fmt[0] == '}') // we're done, no else clause
429                 return fmt.substr(1);
430
431         // else part should follow
432         if (fmt[0] != '[' || fmt[1] != '[') {
433                 LYXERR0("Error parsing  `" << format <<"'. Can't find else clause.");
434                 return format;
435         }
436
437         curfmt = fmt;
438         fmt = getClause(curfmt, elsepart);
439         // we should be done
440         if (fmt == curfmt || fmt[0] != '}') {
441                 LYXERR0("Error parsing  `" << format <<"'. Can't find end of option.");
442                 return format;
443         }
444         return fmt.substr(1);
445 }
446
447
448 } // anon namespace
449
450
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
454 {
455         // incorrect use of macros could put us in an infinite loop
456         static int max_passes = 5000;
457         docstring ret; // return value
458         string key;
459         string lang = buf.params().language->code();
460         bool scanning_key = false;
461         bool scanning_rich = false;
462
463         CiteEngineType const engine_type = buf.params().citeEngineType();
464         string fmt = format;
465         // we'll remove characters from the front of fmt as we
466         // deal with them
467         while (!fmt.empty()) {
468                 if (counter++ > max_passes) {
469                         LYXERR0("Recursion limit reached while parsing `"
470                                 << format << "'.");
471                         return _("ERROR!");
472                 }
473
474                 char_type thischar = fmt[0];
475                 if (thischar == '%') {
476                         // beginning or end of key
477                         if (scanning_key) {
478                                 // end of key
479                                 scanning_key = false;
480                                 // so we replace the key with its value, which may be empty
481                                 if (key[0] == '!') {
482                                         // macro
483                                         // FIXME: instead of passing the buf, just past the macros
484                                         // FIXME: and the language code
485                                         string const val =
486                                                 buf.params().documentClass().getCiteMacro(engine_type, key);
487                                         fmt = val + fmt.substr(1);
488                                         continue;
489                                 } else if (key[0] == '_') {
490                                         // a translatable bit
491                                         string const val =
492                                                 buf.params().documentClass().getCiteMacro(engine_type, key);
493                                         docstring const trans =
494                                                 translateIfPossible(from_utf8(val), lang);
495                                         ret += trans;
496                                 } else {
497                                         docstring const val =
498                                                 getValueForKey(key, before, after, dialog, xref, lang);
499                                         ret += from_ascii("{!<span class=\"bib-" + key + "\">!}");
500                                         ret += val;
501                                         ret += from_ascii("{!</span>!}");
502                                 }
503                         } else {
504                                 // beginning of key
505                                 key.clear();
506                                 scanning_key = true;
507                         }
508                 }
509                 else if (thischar == '{') {
510                         // beginning of option?
511                         if (scanning_key) {
512                                 LYXERR0("ERROR: Found `{' when scanning key in `" << format << "'.");
513                                 return _("ERROR!");
514                         }
515                         if (fmt.size() > 1) {
516                                 if (fmt[1] == '%') {
517                                         // it is the beginning of an optional format
518                                         string optkey;
519                                         string ifpart;
520                                         string elsepart;
521                                         string const newfmt =
522                                                 parseOptions(fmt, optkey, ifpart, elsepart);
523                                         if (newfmt == fmt) // parse error
524                                                 return _("ERROR!");
525                                         fmt = newfmt;
526                                         docstring const val =
527                                                 getValueForKey(optkey, before, after, dialog, xref, lang);
528                                         if (optkey == "next" && next)
529                                                 ret += from_utf8(ifpart); // without expansion
530                                         else if (!val.empty())
531                                                 ret += expandFormat(ifpart, xref, counter, buf,
532                                                         before, after, dialog, next);
533                                         else if (!elsepart.empty())
534                                                 ret += expandFormat(elsepart, xref, counter, buf,
535                                                         before, after, dialog, next);
536                                         // fmt will have been shortened for us already
537                                         continue;
538                                 }
539                                 if (fmt[1] == '!') {
540                                         // beginning of rich text
541                                         scanning_rich = true;
542                                         fmt = fmt.substr(2);
543                                         ret += from_ascii("{!");
544                                         continue;
545                                 }
546                         }
547                         // we are here if '{' was not followed by % or !.
548                         // So it's just a character.
549                         ret += thischar;
550                 }
551                 else if (scanning_rich && thischar == '!'
552                          && fmt.size() > 1 && fmt[1] == '}') {
553                         // end of rich text
554                         scanning_rich = false;
555                         fmt = fmt.substr(2);
556                         ret += from_ascii("!}");
557                         continue;
558                 }
559                 else if (scanning_key)
560                         key += char(thischar);
561                 else
562                         ret += thischar;
563                 fmt = fmt.substr(1);
564         } // for loop
565         if (scanning_key) {
566                 LYXERR0("Never found end of key in `" << format << "'!");
567                 return _("ERROR!");
568         }
569         if (scanning_rich) {
570                 LYXERR0("Never found end of rich text in `" << format << "'!");
571                 return _("ERROR!");
572         }
573         return ret;
574 }
575
576
577 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref,
578         Buffer const & buf, bool richtext) const
579 {
580         if (!richtext && !info_.empty())
581                 return info_;
582         if (richtext && !info_richtext_.empty())
583                 return info_richtext_;
584
585         if (!is_bibtex_) {
586                 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
587                 info_ = it->second;
588                 return info_;
589         }
590
591         CiteEngineType const engine_type = buf.params().citeEngineType();
592         DocumentClass const & dc = buf.params().documentClass();
593         string const & format = dc.getCiteFormat(engine_type, to_utf8(entry_type_));
594         int counter = 0;
595         info_ = expandFormat(format, xref, counter, buf,
596                 docstring(), docstring(), docstring(), false);
597
598         if (!info_.empty()) {
599                 info_richtext_ = convertLaTeXCommands(processRichtext(info_, true));
600                 info_ = convertLaTeXCommands(processRichtext(info_, false));
601                 if (richtext)
602                         return info_richtext_;
603         }
604         return info_;
605 }
606
607
608 docstring const BibTeXInfo::getLabel(BibTeXInfo const * const xref,
609         Buffer const & buf, string const & format, bool richtext,
610         docstring before, docstring after, docstring dialog, bool next) const
611 {
612         docstring loclabel;
613
614         /*
615         if (!is_bibtex_) {
616                 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
617                 label_ = it->second;
618                 return label_;
619         }
620         */
621
622         int counter = 0;
623         loclabel = expandFormat(format, xref, counter, buf,
624                 before, after, dialog, next);
625
626         if (!loclabel.empty() && !next) {
627                 loclabel = processRichtext(loclabel, richtext);
628                 loclabel = convertLaTeXCommands(loclabel);
629         }
630         return loclabel;
631 }
632
633
634 docstring const & BibTeXInfo::operator[](docstring const & field) const
635 {
636         BibTeXInfo::const_iterator it = find(field);
637         if (it != end())
638                 return it->second;
639         static docstring const empty_value = docstring();
640         return empty_value;
641 }
642
643
644 docstring const & BibTeXInfo::operator[](string const & field) const
645 {
646         return operator[](from_ascii(field));
647 }
648
649
650 docstring BibTeXInfo::getValueForKey(string const & key,
651         docstring const & before, docstring const & after, docstring const & dialog,
652         BibTeXInfo const * const xref, string lang) const
653 {
654         docstring ret = operator[](key);
655         if (ret.empty() && xref)
656                 ret = (*xref)[key];
657         if (!ret.empty())
658                 return ret;
659         // some special keys
660         // FIXME: dialog, textbefore and textafter have nothing to do with this
661         if (key == "dialog")
662                 return dialog;
663         else if (key == "entrytype")
664                 return entry_type_;
665         else if (key == "key")
666                 return bib_key_;
667         else if (key == "label")
668                 return label_;
669         else if (key == "abbrvauthor")
670                 // Special key to provide abbreviated author names.
671                 return getAbbreviatedAuthor(false, lang);
672         else if (key == "shortauthor")
673                 // When shortauthor is not defined, jurabib automatically
674                 // provides jurabib-style abbreviated author names. We do
675                 // this as well.
676                 return getAbbreviatedAuthor(true, lang);
677         else if (key == "shorttitle") {
678                 // When shorttitle is not defined, jurabib uses for `article'
679                 // and `periodical' entries the form `journal volume [year]'
680                 // and for other types of entries it uses the `title' field.
681                 if (entry_type_ == "article" || entry_type_ == "periodical")
682                         return operator[]("journal") + " " + operator[]("volume")
683                                 + " [" + operator[]("year") + "]";
684                 else
685                         return operator[]("title");
686         } else if (key == "textbefore")
687                 return before;
688         else if (key == "textafter")
689                 return after;
690         else if (key == "year")
691                 return getYear();
692         return ret;
693 }
694
695
696 //////////////////////////////////////////////////////////////////////
697 //
698 // BiblioInfo
699 //
700 //////////////////////////////////////////////////////////////////////
701
702 namespace {
703
704 // A functor for use with sort, leading to case insensitive sorting
705 class compareNoCase: public binary_function<docstring, docstring, bool>
706 {
707 public:
708         bool operator()(docstring const & s1, docstring const & s2) const {
709                 return compare_no_case(s1, s2) < 0;
710         }
711 };
712
713 } // namespace anon
714
715
716 vector<docstring> const BiblioInfo::getKeys() const
717 {
718         vector<docstring> bibkeys;
719         BiblioInfo::const_iterator it  = begin();
720         for (; it != end(); ++it)
721                 bibkeys.push_back(it->first);
722         sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
723         return bibkeys;
724 }
725
726
727 vector<docstring> const BiblioInfo::getFields() const
728 {
729         vector<docstring> bibfields;
730         set<docstring>::const_iterator it = field_names_.begin();
731         set<docstring>::const_iterator end = field_names_.end();
732         for (; it != end; ++it)
733                 bibfields.push_back(*it);
734         sort(bibfields.begin(), bibfields.end());
735         return bibfields;
736 }
737
738
739 vector<docstring> const BiblioInfo::getEntries() const
740 {
741         vector<docstring> bibentries;
742         set<docstring>::const_iterator it = entry_types_.begin();
743         set<docstring>::const_iterator end = entry_types_.end();
744         for (; it != end; ++it)
745                 bibentries.push_back(*it);
746         sort(bibentries.begin(), bibentries.end());
747         return bibentries;
748 }
749
750
751 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key, string lang) const
752 {
753         BiblioInfo::const_iterator it = find(key);
754         if (it == end())
755                 return docstring();
756         BibTeXInfo const & data = it->second;
757         return data.getAbbreviatedAuthor(false, lang);
758 }
759
760
761 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
762 {
763         BiblioInfo::const_iterator it = find(key);
764         if (it == end())
765                 return docstring();
766         BibTeXInfo const & data = it->second;
767         return data.citeNumber();
768 }
769
770
771 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier, string lang) const
772 {
773         BiblioInfo::const_iterator it = find(key);
774         if (it == end())
775                 return docstring();
776         BibTeXInfo const & data = it->second;
777         docstring year = data.getYear();
778         if (year.empty()) {
779                 // let's try the crossref
780                 docstring const xref = data.getXRef();
781                 if (xref.empty())
782                         // no luck
783                         return translateIfPossible(from_ascii("No year"), lang);
784                 BiblioInfo::const_iterator const xrefit = find(xref);
785                 if (xrefit == end())
786                         // no luck again
787                         return translateIfPossible(from_ascii("No year"), lang);
788                 BibTeXInfo const & xref_data = xrefit->second;
789                 year = xref_data.getYear();
790         }
791         if (use_modifier && data.modifier() != 0)
792                 year += data.modifier();
793         return year;
794 }
795
796
797 docstring const BiblioInfo::getInfo(docstring const & key,
798         Buffer const & buf, bool richtext) const
799 {
800         BiblioInfo::const_iterator it = find(key);
801         if (it == end())
802                 return docstring(_("Bibliography entry not found!"));
803         BibTeXInfo const & data = it->second;
804         BibTeXInfo const * xrefptr = 0;
805         docstring const xref = data.getXRef();
806         if (!xref.empty()) {
807                 BiblioInfo::const_iterator const xrefit = find(xref);
808                 if (xrefit != end())
809                         xrefptr = &(xrefit->second);
810         }
811         return data.getInfo(xrefptr, buf, richtext);
812 }
813
814
815 docstring const BiblioInfo::getLabel(vector<docstring> const & keys,
816         Buffer const & buf, string const & style, bool richtext,
817         docstring const & before, docstring const & after, docstring const & dialog) const
818 {
819         CiteEngineType const engine_type = buf.params().citeEngineType();
820         DocumentClass const & dc = buf.params().documentClass();
821         string const & format = dc.getCiteFormat(engine_type, style, "cite");
822         docstring ret = from_utf8(format);
823         vector<docstring>::const_iterator key = keys.begin();
824         vector<docstring>::const_iterator ken = keys.end();
825         for (; key != ken; ++key) {
826                 BiblioInfo::const_iterator it = find(*key);
827                 BibTeXInfo empty_data;
828                 empty_data.key(*key);
829                 BibTeXInfo & data = empty_data;
830                 BibTeXInfo const * xrefptr = 0;
831                 if (it != end()) {
832                         data = it->second;
833                         docstring const xref = data.getXRef();
834                         if (!xref.empty()) {
835                                 BiblioInfo::const_iterator const xrefit = find(xref);
836                                 if (xrefit != end())
837                                         xrefptr = &(xrefit->second);
838                         }
839                 }
840                 ret = data.getLabel(xrefptr, buf, to_utf8(ret), richtext,
841                         before, after, dialog, key+1 != ken);
842         }
843         return ret;
844 }
845
846
847 bool BiblioInfo::isBibtex(docstring const & key) const
848 {
849         BiblioInfo::const_iterator it = find(key);
850         if (it == end())
851                 return false;
852         return it->second.isBibTeX();
853 }
854
855
856 vector<docstring> const BiblioInfo::getCiteStrings(
857         vector<docstring> const & keys, vector<CitationStyle> const & styles,
858         Buffer const & buf, bool richtext, docstring const & before,
859         docstring const & after, docstring const & dialog) const
860 {
861         if (empty())
862                 return vector<docstring>();
863
864         string style;
865         vector<docstring> vec(styles.size());
866         for (size_t i = 0; i != vec.size(); ++i) {
867                 style = styles[i].cmd;
868                 vec[i] = getLabel(keys, buf, style, richtext, before, after, dialog);
869         }
870
871         return vec;
872 }
873
874
875 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
876 {
877         bimap_.insert(info.begin(), info.end());
878         field_names_.insert(info.field_names_.begin(), info.field_names_.end());
879         entry_types_.insert(info.entry_types_.begin(), info.entry_types_.end());
880 }
881
882
883 namespace {
884
885 // used in xhtml to sort a list of BibTeXInfo objects
886 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
887 {
888         docstring const lauth = lhs->getAbbreviatedAuthor();
889         docstring const rauth = rhs->getAbbreviatedAuthor();
890         docstring const lyear = lhs->getYear();
891         docstring const ryear = rhs->getYear();
892         docstring const ltitl = lhs->operator[]("title");
893         docstring const rtitl = rhs->operator[]("title");
894         return  (lauth < rauth)
895                 || (lauth == rauth && lyear < ryear)
896                 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
897 }
898
899 }
900
901
902 void BiblioInfo::collectCitedEntries(Buffer const & buf)
903 {
904         cited_entries_.clear();
905         // We are going to collect all the citation keys used in the document,
906         // getting them from the TOC.
907         // FIXME We may want to collect these differently, in the first case,
908         // so that we might have them in order of appearance.
909         set<docstring> citekeys;
910         Toc const & toc = buf.tocBackend().toc("citation");
911         Toc::const_iterator it = toc.begin();
912         Toc::const_iterator const en = toc.end();
913         for (; it != en; ++it) {
914                 if (it->str().empty())
915                         continue;
916                 vector<docstring> const keys = getVectorFromString(it->str());
917                 citekeys.insert(keys.begin(), keys.end());
918         }
919         if (citekeys.empty())
920                 return;
921
922         // We have a set of the keys used in this document.
923         // We will now convert it to a list of the BibTeXInfo objects used in
924         // this document...
925         vector<BibTeXInfo const *> bi;
926         set<docstring>::const_iterator cit = citekeys.begin();
927         set<docstring>::const_iterator const cen = citekeys.end();
928         for (; cit != cen; ++cit) {
929                 BiblioInfo::const_iterator const bt = find(*cit);
930                 if (bt == end() || !bt->second.isBibTeX())
931                         continue;
932                 bi.push_back(&(bt->second));
933         }
934         // ...and sort it.
935         sort(bi.begin(), bi.end(), lSorter);
936
937         // Now we can write the sorted keys
938         vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
939         vector<BibTeXInfo const *>::const_iterator ben = bi.end();
940         for (; bit != ben; ++bit)
941                 cited_entries_.push_back((*bit)->key());
942 }
943
944
945 void BiblioInfo::makeCitationLabels(Buffer const & buf)
946 {
947         collectCitedEntries(buf);
948         CiteEngineType const engine_type = buf.params().citeEngineType();
949         bool const numbers = (engine_type == ENGINE_TYPE_NUMERICAL);
950
951         int keynumber = 0;
952         char modifier = 0;
953         // used to remember the last one we saw
954         // we'll be comparing entries to see if we need to add
955         // modifiers, like "1984a"
956         map<docstring, BibTeXInfo>::iterator last;
957
958         vector<docstring>::const_iterator it = cited_entries_.begin();
959         vector<docstring>::const_iterator const en = cited_entries_.end();
960         for (; it != en; ++it) {
961                 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
962                 // this shouldn't happen, but...
963                 if (biit == bimap_.end())
964                         // ...fail gracefully, anyway.
965                         continue;
966                 BibTeXInfo & entry = biit->second;
967                 if (numbers) {
968                         docstring const num = convert<docstring>(++keynumber);
969                         entry.setCiteNumber(num);
970                 } else {
971                         if (it != cited_entries_.begin()
972                             && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
973                             // we access the year via getYear() so as to get it from the xref,
974                             // if we need to do so
975                             && getYear(entry.key()) == getYear(last->second.key())) {
976                                 if (modifier == 0) {
977                                         // so the last one should have been 'a'
978                                         last->second.setModifier('a');
979                                         modifier = 'b';
980                                 } else if (modifier == 'z')
981                                         modifier = 'A';
982                                 else
983                                         modifier++;
984                         } else {
985                                 modifier = 0;
986                         }
987                         entry.setModifier(modifier);
988                         // remember the last one
989                         last = biit;
990                 }
991         }
992 }
993
994
995 //////////////////////////////////////////////////////////////////////
996 //
997 // CitationStyle
998 //
999 //////////////////////////////////////////////////////////////////////
1000
1001
1002 CitationStyle citationStyleFromString(string const & command)
1003 {
1004         CitationStyle cs;
1005         if (command.empty())
1006                 return cs;
1007
1008         string cmd = command;
1009         if (cmd[0] == 'C') {
1010                 cs.forceUpperCase = true;
1011                 cmd[0] = 'c';
1012         }
1013
1014         size_t const n = cmd.size() - 1;
1015         if (cmd[n] == '*') {
1016                 cs.fullAuthorList = true;
1017                 cmd = cmd.substr(0, n);
1018         }
1019
1020         cs.cmd = cmd;
1021         return cs;
1022 }
1023
1024
1025 string citationStyleToString(const CitationStyle & cs)
1026 {
1027         string cmd = cs.cmd;
1028         if (cs.forceUpperCase)
1029                 cmd[0] = 'C';
1030         if (cs.fullAuthorList)
1031                 cmd += '*';
1032         return cmd;
1033 }
1034
1035 } // namespace lyx