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