]> git.lyx.org Git - lyx.git/blob - src/BiblioInfo.cpp
- moderncv.layout: add missing separator style
[lyx.git] / src / BiblioInfo.cpp
1 /**
2  * \file BiblioInfo.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  * \author Herbert Voß
8  * \author Richard Heck
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "BiblioInfo.h"
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "buffer_funcs.h"
19 #include "Encoding.h"
20 #include "InsetIterator.h"
21 #include "Language.h"
22 #include "Paragraph.h"
23 #include "TextClass.h"
24 #include "TocBackend.h"
25
26 #include "support/convert.h"
27 #include "support/debug.h"
28 #include "support/docstream.h"
29 #include "support/gettext.h"
30 #include "support/lassert.h"
31 #include "support/lstrings.h"
32 #include "support/regex.h"
33 #include "support/textutils.h"
34
35 #include <set>
36
37 using namespace std;
38 using namespace lyx::support;
39
40
41 namespace lyx {
42
43 namespace {
44
45 // gets the "family name" from an author-type string
46 docstring familyName(docstring const & name)
47 {
48         if (name.empty())
49                 return docstring();
50
51         // first we look for a comma, and take the last name to be everything
52         // preceding the right-most one, so that we also get the "jr" part.
53         docstring::size_type idx = name.rfind(',');
54         if (idx != docstring::npos)
55                 return ltrim(name.substr(0, idx));
56
57         // OK, so now we want to look for the last name. We're going to
58         // include the "von" part. This isn't perfect.
59         // Split on spaces, to get various tokens.
60         vector<docstring> pieces = getVectorFromString(name, from_ascii(" "));
61         // If we only get two, assume the last one is the last name
62         if (pieces.size() <= 2)
63                 return pieces.back();
64
65         // Now we look for the first token that begins with a lower case letter.
66         vector<docstring>::const_iterator it = pieces.begin();
67         vector<docstring>::const_iterator en = pieces.end();
68         for (; it != en; ++it) {
69                 if ((*it).size() == 0)
70                         continue;
71                 char_type const c = (*it)[0];
72                 if (isLower(c))
73                         break;
74         }
75
76         if (it == en) // we never found a "von"
77                 return pieces.back();
78
79         // reconstruct what we need to return
80         docstring retval;
81         bool first = true;
82         for (; it != en; ++it) {
83                 if (!first)
84                         retval += " ";
85                 else
86                         first = false;
87                 retval += *it;
88         }
89         return retval;
90 }
91
92 // converts a string containing LaTeX commands into unicode
93 // for display.
94 docstring convertLaTeXCommands(docstring const & str)
95 {
96         docstring val = str;
97         docstring ret;
98
99         bool scanning_cmd = false;
100         bool scanning_math = false;
101         bool escaped = false; // used to catch \$, etc.
102         while (val.size()) {
103                 char_type const ch = val[0];
104
105                 // if we're scanning math, we output everything until we
106                 // find an unescaped $, at which point we break out.
107                 if (scanning_math) {
108                         if (escaped)
109                                 escaped = false;
110                         else if (ch == '\\')
111                                 escaped = true;
112                         else if (ch == '$')
113                                 scanning_math = false;
114                         ret += ch;
115                         val = val.substr(1);
116                         continue;
117                 }
118
119                 // if we're scanning a command name, then we just
120                 // discard characters until we hit something that
121                 // isn't alpha.
122                 if (scanning_cmd) {
123                         if (isAlphaASCII(ch)) {
124                                 val = val.substr(1);
125                                 escaped = false;
126                                 continue;
127                         }
128                         // so we're done with this command.
129                         // now we fall through and check this character.
130                         scanning_cmd = false;
131                 }
132
133                 // was the last character a \? If so, then this is something like:
134                 // \\ or \$, so we'll just output it. That's probably not always right...
135                 if (escaped) {
136                         // exception: output \, as THIN SPACE
137                         if (ch == ',')
138                                 ret.push_back(0x2009);
139                         else
140                                 ret += ch;
141                         val = val.substr(1);
142                         escaped = false;
143                         continue;
144                 }
145
146                 if (ch == '$') {
147                         ret += ch;
148                         val = val.substr(1);
149                         scanning_math = true;
150                         continue;
151                 }
152
153                 // we just ignore braces
154                 if (ch == '{' || ch == '}') {
155                         val = val.substr(1);
156                         continue;
157                 }
158
159                 // we're going to check things that look like commands, so if
160                 // this doesn't, just output it.
161                 if (ch != '\\') {
162                         ret += ch;
163                         val = val.substr(1);
164                         continue;
165                 }
166
167                 // ok, could be a command of some sort
168                 // let's see if it corresponds to some unicode
169                 // unicodesymbols has things in the form: \"{u},
170                 // whereas we may see things like: \"u. So we'll
171                 // look for that and change it, if necessary.
172                 static lyx::regex const reg("^\\\\\\W\\w");
173                 if (lyx::regex_search(to_utf8(val), reg)) {
174                         val.insert(3, from_ascii("}"));
175                         val.insert(2, from_ascii("{"));
176                 }
177                 docstring rem;
178                 docstring const cnvtd = Encodings::fromLaTeXCommand(val,
179                                 Encodings::TEXT_CMD, rem);
180                 if (!cnvtd.empty()) {
181                         // it did, so we'll take that bit and proceed with what's left
182                         ret += cnvtd;
183                         val = rem;
184                         continue;
185                 }
186                 // it's a command of some sort
187                 scanning_cmd = true;
188                 escaped = true;
189                 val = val.substr(1);
190         }
191         return ret;
192 }
193
194 } // anon namespace
195
196
197 //////////////////////////////////////////////////////////////////////
198 //
199 // BibTeXInfo
200 //
201 //////////////////////////////////////////////////////////////////////
202
203 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
204         : is_bibtex_(true), bib_key_(key), entry_type_(type), info_(),
205           modifier_(0)
206 {}
207
208
209 docstring const BibTeXInfo::getAbbreviatedAuthor() 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(_("Bibliography 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         CiteEngineType const engine_type = buf.params().citeEngineType();
696         if (engine_type == ENGINE_TYPE_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                 buf.params().citeEngineType());
716
717         vector<docstring> vec(styles.size());
718         for (size_t i = 0; i != vec.size(); ++i) {
719                 docstring str;
720
721                 switch (styles[i]) {
722                         case CITE:
723                         case CITEP:
724                                 str = from_ascii("[#ID]");
725                                 break;
726
727                         case NOCITE:
728                                 str = _("Add to bibliography only.");
729                                 break;
730
731                         case CITET:
732                                 str = author + " [#ID]";
733                                 break;
734
735                         case CITEALT:
736                                 str = author + " #ID";
737                                 break;
738
739                         case CITEALP:
740                                 str = from_ascii("#ID");
741                                 break;
742
743                         case CITEAUTHOR:
744                                 str = author;
745                                 break;
746
747                         case CITEYEAR:
748                                 str = year;
749                                 break;
750
751                         case CITEYEARPAR:
752                                 str = '(' + year + ')';
753                                 break;
754                 }
755
756                 vec[i] = str;
757         }
758
759         return vec;
760 }
761
762
763 vector<docstring> const BiblioInfo::getAuthorYearStrings(
764         docstring const & key, Buffer const & buf) const
765 {
766         if (empty())
767                 return vector<docstring>();
768
769         docstring const author = getAbbreviatedAuthor(key);
770         docstring const year   = getYear(key);
771         if (author.empty() || year.empty())
772                 return vector<docstring>();
773
774         vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine(),
775                 buf.params().citeEngineType());
776
777         vector<docstring> vec(styles.size());
778         for (size_t i = 0; i != vec.size(); ++i) {
779                 docstring str;
780
781                 switch (styles[i]) {
782                         case CITE:
783                 // jurabib only: Author/Annotator
784                 // (i.e. the "before" field, 2nd opt arg)
785                                 str = author + "/<" + _("before") + '>';
786                                 break;
787
788                         case NOCITE:
789                                 str = _("Add to bibliography only.");
790                                 break;
791
792                         case CITET:
793                                 str = author + " (" + year + ')';
794                                 break;
795
796                         case CITEP:
797                                 str = '(' + author + ", " + year + ')';
798                                 break;
799
800                         case CITEALT:
801                                 str = author + ' ' + year ;
802                                 break;
803
804                         case CITEALP:
805                                 str = author + ", " + year ;
806                                 break;
807
808                         case CITEAUTHOR:
809                                 str = author;
810                                 break;
811
812                         case CITEYEAR:
813                                 str = year;
814                                 break;
815
816                         case CITEYEARPAR:
817                                 str = '(' + year + ')';
818                                 break;
819                 }
820                 vec[i] = str;
821         }
822         return vec;
823 }
824
825
826 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
827 {
828         bimap_.insert(info.begin(), info.end());
829         field_names_.insert(info.field_names_.begin(), info.field_names_.end());
830         entry_types_.insert(info.entry_types_.begin(), info.entry_types_.end());
831 }
832
833
834 namespace {
835         // used in xhtml to sort a list of BibTeXInfo objects
836         bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
837         {
838                 docstring const lauth = lhs->getAbbreviatedAuthor();
839                 docstring const rauth = rhs->getAbbreviatedAuthor();
840                 docstring const lyear = lhs->getYear();
841                 docstring const ryear = rhs->getYear();
842                 docstring const ltitl = lhs->operator[]("title");
843                 docstring const rtitl = rhs->operator[]("title");
844                 return  (lauth < rauth)
845                                 || (lauth == rauth && lyear < ryear)
846                                 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
847         }
848 }
849
850
851 void BiblioInfo::collectCitedEntries(Buffer const & buf)
852 {
853         cited_entries_.clear();
854         // We are going to collect all the citation keys used in the document,
855         // getting them from the TOC.
856         // FIXME We may want to collect these differently, in the first case,
857         // so that we might have them in order of appearance.
858         set<docstring> citekeys;
859         Toc const & toc = buf.tocBackend().toc("citation");
860         Toc::const_iterator it = toc.begin();
861         Toc::const_iterator const en = toc.end();
862         for (; it != en; ++it) {
863                 if (it->str().empty())
864                         continue;
865                 vector<docstring> const keys = getVectorFromString(it->str());
866                 citekeys.insert(keys.begin(), keys.end());
867         }
868         if (citekeys.empty())
869                 return;
870
871         // We have a set of the keys used in this document.
872         // We will now convert it to a list of the BibTeXInfo objects used in
873         // this document...
874         vector<BibTeXInfo const *> bi;
875         set<docstring>::const_iterator cit = citekeys.begin();
876         set<docstring>::const_iterator const cen = citekeys.end();
877         for (; cit != cen; ++cit) {
878                 BiblioInfo::const_iterator const bt = find(*cit);
879                 if (bt == end() || !bt->second.isBibTeX())
880                         continue;
881                 bi.push_back(&(bt->second));
882         }
883         // ...and sort it.
884         sort(bi.begin(), bi.end(), lSorter);
885
886         // Now we can write the sorted keys
887         vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
888         vector<BibTeXInfo const *>::const_iterator ben = bi.end();
889         for (; bit != ben; ++bit)
890                 cited_entries_.push_back((*bit)->key());
891 }
892
893
894 void BiblioInfo::makeCitationLabels(Buffer const & buf)
895 {
896         collectCitedEntries(buf);
897         CiteEngineType const engine_type = buf.params().citeEngineType();
898         bool const numbers = (engine_type == ENGINE_TYPE_NUMERICAL);
899
900         int keynumber = 0;
901         char modifier = 0;
902         // used to remember the last one we saw
903         // we'll be comparing entries to see if we need to add
904         // modifiers, like "1984a"
905         map<docstring, BibTeXInfo>::iterator last;
906
907         vector<docstring>::const_iterator it = cited_entries_.begin();
908         vector<docstring>::const_iterator const en = cited_entries_.end();
909         for (; it != en; ++it) {
910                 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
911                 // this shouldn't happen, but...
912                 if (biit == bimap_.end())
913                         // ...fail gracefully, anyway.
914                         continue;
915                 BibTeXInfo & entry = biit->second;
916                 if (numbers) {
917                         docstring const num = convert<docstring>(++keynumber);
918                         entry.setCiteNumber(num);
919                 } else {
920                         if (it != cited_entries_.begin()
921                             && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
922                             // we access the year via getYear() so as to get it from the xref,
923                             // if we need to do so
924                             && getYear(entry.key()) == getYear(last->second.key())) {
925                                 if (modifier == 0) {
926                                         // so the last one should have been 'a'
927                                         last->second.setModifier('a');
928                                         modifier = 'b';
929                                 } else if (modifier == 'z')
930                                         modifier = 'A';
931                                 else
932                                         modifier++;
933                         } else {
934                                 modifier = 0;
935                         }
936                         entry.setModifier(modifier);
937                         // remember the last one
938                         last = biit;
939                 }
940         }
941 }
942
943
944 //////////////////////////////////////////////////////////////////////
945 //
946 // CitationStyle
947 //
948 //////////////////////////////////////////////////////////////////////
949
950 namespace {
951
952
953 char const * const citeCommands[] = {
954         "cite", "citet", "citep", "citealt", "citealp",
955         "citeauthor", "citeyear", "citeyearpar", "nocite" };
956
957 unsigned int const nCiteCommands =
958                 sizeof(citeCommands) / sizeof(char *);
959
960 CiteStyle const citeStylesArray[] = {
961         CITE, CITET, CITEP, CITEALT, CITEALP, 
962         CITEAUTHOR, CITEYEAR, CITEYEARPAR, NOCITE };
963
964 unsigned int const nCiteStyles =
965                 sizeof(citeStylesArray) / sizeof(CiteStyle);
966
967 CiteStyle const citeStylesFull[] = {
968         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
969
970 unsigned int const nCiteStylesFull =
971                 sizeof(citeStylesFull) / sizeof(CiteStyle);
972
973 CiteStyle const citeStylesUCase[] = {
974         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
975
976 unsigned int const nCiteStylesUCase =
977         sizeof(citeStylesUCase) / sizeof(CiteStyle);
978
979 } // namespace anon
980
981
982 CitationStyle citationStyleFromString(string const & command)
983 {
984         CitationStyle s;
985         if (command.empty())
986                 return s;
987
988         string cmd = command;
989         if (cmd[0] == 'C') {
990                 s.forceUpperCase = true;
991                 cmd[0] = 'c';
992         }
993
994         size_t const n = cmd.size() - 1;
995         if (cmd != "cite" && cmd[n] == '*') {
996                 s.full = true;
997                 cmd = cmd.substr(0, n);
998         }
999
1000         char const * const * const last = citeCommands + nCiteCommands;
1001         char const * const * const ptr = find(citeCommands, last, cmd);
1002
1003         if (ptr != last) {
1004                 size_t idx = ptr - citeCommands;
1005                 s.style = citeStylesArray[idx];
1006         }
1007         return s;
1008 }
1009
1010
1011 string citationStyleToString(const CitationStyle & s)
1012 {
1013         string cite = citeCommands[s.style];
1014         if (s.full) {
1015                 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
1016                 if (std::find(citeStylesFull, last, s.style) != last)
1017                         cite += '*';
1018         }
1019
1020         if (s.forceUpperCase) {
1021                 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
1022                 if (std::find(citeStylesUCase, last, s.style) != last)
1023                         cite[0] = 'C';
1024         }
1025
1026         return cite;
1027 }
1028
1029 vector<CiteStyle> citeStyles(CiteEngine engine, CiteEngineType engine_type)
1030 {
1031         vector<CiteStyle> styles(0);
1032
1033         if (engine_type == ENGINE_TYPE_AUTHORYEAR) {
1034                 switch (engine) {
1035                 case ENGINE_BASIC:
1036                         styles.push_back(CITE);
1037                         break;
1038                 case ENGINE_JURABIB:
1039                         styles.push_back(CITE);
1040                 case ENGINE_NATBIB:
1041                         styles.push_back(CITET);
1042                         styles.push_back(CITEP);
1043                         styles.push_back(CITEALT);
1044                         styles.push_back(CITEALP);
1045                         styles.push_back(CITEAUTHOR);
1046                         styles.push_back(CITEYEAR);
1047                         styles.push_back(CITEYEARPAR);
1048                         break;
1049                 }
1050         } else {
1051                 switch (engine) {
1052                 case ENGINE_BASIC:
1053                         styles.push_back(CITE);
1054                         break;
1055                 case ENGINE_JURABIB:
1056                         styles.push_back(CITE);
1057                 case ENGINE_NATBIB:
1058                         styles.push_back(CITET);
1059                         styles.push_back(CITEALT);
1060                         styles.push_back(CITEAUTHOR);
1061                         styles.push_back(CITEP);
1062                         styles.push_back(CITEALP);
1063                         styles.push_back(CITEYEAR);
1064                         styles.push_back(CITEYEARPAR);
1065                         break;
1066                 }
1067         }
1068
1069         styles.push_back(NOCITE);
1070
1071         return styles;
1072 }
1073
1074 } // namespace lyx
1075