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