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