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