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