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