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