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