]> git.lyx.org Git - lyx.git/blob - src/BiblioInfo.cpp
c031058aa341f76201acd0b62ea89b9be5081649
[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 "support/regex.h"
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 lyx::regex const reg("^\\\\\\W\\w");
179                 if (lyx::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) {
495                         if (scanning_rich)
496                                 ret += thischar;
497                         else {
498                                 // we need to escape '<' and '>'
499                                 if (thischar == '<')
500                                         ret += "&lt;";
501                                 else if (thischar == '>')
502                                         ret += "&gt;";
503                                 else 
504                                         ret += thischar;
505                         }       
506                 }       else if (!scanning_rich /* && !richtext */)
507                         ret += thischar;
508                 // else the character is discarded, which will happen only if
509                 // richtext == false and we are scanning rich text
510                 fmt = fmt.substr(1);
511         } // for loop
512         if (scanning_key) {
513                 LYXERR0("Never found end of key in `" << format << "'!");
514                 return _("ERROR!");
515         }
516         if (scanning_rich) {
517                 LYXERR0("Never found end of rich text in `" << format << "'!");
518                 return _("ERROR!");
519         }
520         return ret;
521 }
522
523
524 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref,
525         Buffer const & buf, bool richtext) const
526 {
527         if (!info_.empty())
528                 return info_;
529
530         if (!is_bibtex_) {
531                 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
532                 info_ = it->second;
533                 return info_;
534         }
535
536         DocumentClass const & dc = buf.params().documentClass();
537         string const & format = dc.getCiteFormat(to_utf8(entry_type_));
538         int counter = 0;
539         info_ = expandFormat(format, xref, counter, buf, richtext);
540
541         if (!info_.empty())
542                 info_ = convertLaTeXCommands(info_);
543         return info_;
544 }
545
546
547 docstring const & BibTeXInfo::operator[](docstring const & field) const
548 {
549         BibTeXInfo::const_iterator it = find(field);
550         if (it != end())
551                 return it->second;
552         static docstring const empty_value = docstring();
553         return empty_value;
554 }
555         
556         
557 docstring const & BibTeXInfo::operator[](string const & field) const
558 {
559         return operator[](from_ascii(field));
560 }
561
562
563 docstring BibTeXInfo::getValueForKey(string const & key, 
564                 BibTeXInfo const * const xref) const
565 {
566         docstring const ret = operator[](key);
567         if (!ret.empty() || !xref)
568                 return ret;
569         return (*xref)[key];
570 }
571
572
573 //////////////////////////////////////////////////////////////////////
574 //
575 // BiblioInfo
576 //
577 //////////////////////////////////////////////////////////////////////
578
579 namespace {
580 // A functor for use with sort, leading to case insensitive sorting
581         class compareNoCase: public binary_function<docstring, docstring, bool>
582         {
583                 public:
584                         bool operator()(docstring const & s1, docstring const & s2) const {
585                                 return compare_no_case(s1, s2) < 0;
586                         }
587         };
588 } // namespace anon
589
590
591 vector<docstring> const BiblioInfo::getKeys() const
592 {
593         vector<docstring> bibkeys;
594         BiblioInfo::const_iterator it  = begin();
595         for (; it != end(); ++it)
596                 bibkeys.push_back(it->first);
597         sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
598         return bibkeys;
599 }
600
601
602 vector<docstring> const BiblioInfo::getFields() const
603 {
604         vector<docstring> bibfields;
605         set<docstring>::const_iterator it = field_names_.begin();
606         set<docstring>::const_iterator end = field_names_.end();
607         for (; it != end; ++it)
608                 bibfields.push_back(*it);
609         sort(bibfields.begin(), bibfields.end());
610         return bibfields;
611 }
612
613
614 vector<docstring> const BiblioInfo::getEntries() const
615 {
616         vector<docstring> bibentries;
617         set<docstring>::const_iterator it = entry_types_.begin();
618         set<docstring>::const_iterator end = entry_types_.end();
619         for (; it != end; ++it)
620                 bibentries.push_back(*it);
621         sort(bibentries.begin(), bibentries.end());
622         return bibentries;
623 }
624
625
626 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
627 {
628         BiblioInfo::const_iterator it = find(key);
629         if (it == end())
630                 return docstring();
631         BibTeXInfo const & data = it->second;
632         return data.getAbbreviatedAuthor();
633 }
634
635
636 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
637 {
638         BiblioInfo::const_iterator it = find(key);
639         if (it == end())
640                 return docstring();
641         BibTeXInfo const & data = it->second;
642         return data.citeNumber();
643 }
644
645
646 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier) const
647 {
648         BiblioInfo::const_iterator it = find(key);
649         if (it == end())
650                 return docstring();
651         BibTeXInfo const & data = it->second;
652         docstring year = data.getYear();
653         if (year.empty()) {
654                 // let's try the crossref
655                 docstring const xref = data.getXRef();
656                 if (xref.empty())
657                         return _("No year"); // no luck
658                 BiblioInfo::const_iterator const xrefit = find(xref);
659                 if (xrefit == end())
660                         return _("No year"); // no luck again
661                 BibTeXInfo const & xref_data = xrefit->second;
662                 year = xref_data.getYear();
663         }
664         if (use_modifier && data.modifier() != 0)
665                 year += data.modifier();
666         return year;
667 }
668
669
670 docstring const BiblioInfo::getInfo(docstring const & key, 
671         Buffer const & buf, bool richtext) const
672 {
673         BiblioInfo::const_iterator it = find(key);
674         if (it == end())
675                 return docstring();
676         BibTeXInfo const & data = it->second;
677         BibTeXInfo const * xrefptr = 0;
678         docstring const xref = data.getXRef();
679         if (!xref.empty()) {
680                 BiblioInfo::const_iterator const xrefit = find(xref);
681                 if (xrefit != end())
682                         xrefptr = &(xrefit->second);
683         }
684         return data.getInfo(xrefptr, buf, richtext);
685 }
686
687
688 bool BiblioInfo::isBibtex(docstring const & key) const
689 {
690         BiblioInfo::const_iterator it = find(key);
691         if (it == end())
692                 return false;
693         return it->second.isBibTeX();
694 }
695
696
697
698 vector<docstring> const BiblioInfo::getCiteStrings(
699         docstring const & key, Buffer const & buf) const
700 {
701         CiteEngine const engine = buf.params().citeEngine();
702         if (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL)
703                 return getNumericalStrings(key, buf);
704         else
705                 return getAuthorYearStrings(key, buf);
706 }
707
708
709 vector<docstring> const BiblioInfo::getNumericalStrings(
710         docstring const & key, Buffer const & buf) const
711 {
712         if (empty())
713                 return vector<docstring>();
714
715         docstring const author = getAbbreviatedAuthor(key);
716         docstring const year   = getYear(key);
717         if (author.empty() || year.empty())
718                 return vector<docstring>();
719
720         vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
721         
722         vector<docstring> vec(styles.size());
723         for (size_t i = 0; i != vec.size(); ++i) {
724                 docstring str;
725
726                 switch (styles[i]) {
727                         case CITE:
728                         case CITEP:
729                                 str = from_ascii("[#ID]");
730                                 break;
731
732                         case NOCITE:
733                                 str = _("Add to bibliography only.");
734                                 break;
735
736                         case CITET:
737                                 str = author + " [#ID]";
738                                 break;
739
740                         case CITEALT:
741                                 str = author + " #ID";
742                                 break;
743
744                         case CITEALP:
745                                 str = from_ascii("#ID");
746                                 break;
747
748                         case CITEAUTHOR:
749                                 str = author;
750                                 break;
751
752                         case CITEYEAR:
753                                 str = year;
754                                 break;
755
756                         case CITEYEARPAR:
757                                 str = '(' + year + ')';
758                                 break;
759                 }
760
761                 vec[i] = str;
762         }
763
764         return vec;
765 }
766
767
768 vector<docstring> const BiblioInfo::getAuthorYearStrings(
769         docstring const & key, Buffer const & buf) const
770 {
771         if (empty())
772                 return vector<docstring>();
773
774         docstring const author = getAbbreviatedAuthor(key);
775         docstring const year   = getYear(key);
776         if (author.empty() || year.empty())
777                 return vector<docstring>();
778
779         vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
780         
781         vector<docstring> vec(styles.size());
782         for (size_t i = 0; i != vec.size(); ++i) {
783                 docstring str;
784
785                 switch (styles[i]) {
786                         case CITE:
787                 // jurabib only: Author/Annotator
788                 // (i.e. the "before" field, 2nd opt arg)
789                                 str = author + "/<" + _("before") + '>';
790                                 break;
791
792                         case NOCITE:
793                                 str = _("Add to bibliography only.");
794                                 break;
795
796                         case CITET:
797                                 str = author + " (" + year + ')';
798                                 break;
799
800                         case CITEP:
801                                 str = '(' + author + ", " + year + ')';
802                                 break;
803
804                         case CITEALT:
805                                 str = author + ' ' + year ;
806                                 break;
807
808                         case CITEALP:
809                                 str = author + ", " + year ;
810                                 break;
811
812                         case CITEAUTHOR:
813                                 str = author;
814                                 break;
815
816                         case CITEYEAR:
817                                 str = year;
818                                 break;
819
820                         case CITEYEARPAR:
821                                 str = '(' + year + ')';
822                                 break;
823                 }
824                 vec[i] = str;
825         }
826         return vec;
827 }
828
829
830 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
831 {
832         bimap_.insert(info.begin(), info.end());
833         field_names_.insert(info.field_names_.begin(), info.field_names_.end());
834         entry_types_.insert(info.entry_types_.begin(), info.entry_types_.end());
835 }
836
837
838 namespace {
839         // used in xhtml to sort a list of BibTeXInfo objects
840         bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
841         {
842                 docstring const lauth = lhs->getAbbreviatedAuthor();
843                 docstring const rauth = rhs->getAbbreviatedAuthor();
844                 docstring const lyear = lhs->getYear();
845                 docstring const ryear = rhs->getYear();
846                 docstring const ltitl = lhs->operator[]("title");
847                 docstring const rtitl = rhs->operator[]("title");
848                 return  (lauth < rauth)
849                                 || (lauth == rauth && lyear < ryear)
850                                 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
851         }
852 }
853
854
855 void BiblioInfo::collectCitedEntries(Buffer const & buf)
856 {
857         cited_entries_.clear();
858         // We are going to collect all the citation keys used in the document,
859         // getting them from the TOC.
860         // FIXME We may want to collect these differently, in the first case,
861         // so that we might have them in order of appearance.
862         set<docstring> citekeys;
863         Toc const & toc = buf.tocBackend().toc("citation");
864         Toc::const_iterator it = toc.begin();
865         Toc::const_iterator const en = toc.end();
866         for (; it != en; ++it) {
867                 if (it->str().empty())
868                         continue;
869                 vector<docstring> const keys = getVectorFromString(it->str());
870                 citekeys.insert(keys.begin(), keys.end());
871         }
872         if (citekeys.empty())
873                 return;
874         
875         // We have a set of the keys used in this document.
876         // We will now convert it to a list of the BibTeXInfo objects used in 
877         // this document...
878         vector<BibTeXInfo const *> bi;
879         set<docstring>::const_iterator cit = citekeys.begin();
880         set<docstring>::const_iterator const cen = citekeys.end();
881         for (; cit != cen; ++cit) {
882                 BiblioInfo::const_iterator const bt = find(*cit);
883                 if (bt == end() || !bt->second.isBibTeX())
884                         continue;
885                 bi.push_back(&(bt->second));
886         }
887         // ...and sort it.
888         sort(bi.begin(), bi.end(), lSorter);
889         
890         // Now we can write the sorted keys
891         vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
892         vector<BibTeXInfo const *>::const_iterator ben = bi.end();
893         for (; bit != ben; ++bit)
894                 cited_entries_.push_back((*bit)->key());
895 }
896
897
898 void BiblioInfo::makeCitationLabels(Buffer const & buf)
899 {
900         collectCitedEntries(buf);
901         CiteEngine const engine = buf.params().citeEngine();
902         bool const numbers = 
903                 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
904
905         int keynumber = 0;
906         char modifier = 0;
907         // used to remember the last one we saw
908         // we'll be comparing entries to see if we need to add
909         // modifiers, like "1984a"
910         map<docstring, BibTeXInfo>::iterator last;
911
912         vector<docstring>::const_iterator it = cited_entries_.begin();
913         vector<docstring>::const_iterator const en = cited_entries_.end();
914         for (; it != en; ++it) {
915                 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
916                 // this shouldn't happen, but...
917                 if (biit == bimap_.end())
918                         // ...fail gracefully, anyway.
919                         continue;
920                 BibTeXInfo & entry = biit->second;
921                 if (numbers) {
922                         docstring const num = convert<docstring>(++keynumber);
923                         entry.setCiteNumber(num);
924                 } else {
925                         if (it != cited_entries_.begin()
926                             && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
927                             // we access the year via getYear() so as to get it from the xref,
928                             // if we need to do so
929                             && getYear(entry.key()) == getYear(last->second.key())) {
930                                 if (modifier == 0) {
931                                         // so the last one should have been 'a'
932                                         last->second.setModifier('a');
933                                         modifier = 'b';
934                                 } else if (modifier == 'z')
935                                         modifier = 'A';
936                                 else
937                                         modifier++;
938                         } else {
939                                 modifier = 0;
940                         }
941                         entry.setModifier(modifier);                            
942                         // remember the last one
943                         last = biit;
944                 }
945         }
946 }
947
948
949 //////////////////////////////////////////////////////////////////////
950 //
951 // CitationStyle
952 //
953 //////////////////////////////////////////////////////////////////////
954
955 namespace {
956
957
958 char const * const citeCommands[] = {
959         "cite", "citet", "citep", "citealt", "citealp",
960         "citeauthor", "citeyear", "citeyearpar", "nocite" };
961
962 unsigned int const nCiteCommands =
963                 sizeof(citeCommands) / sizeof(char *);
964
965 CiteStyle const citeStylesArray[] = {
966         CITE, CITET, CITEP, CITEALT, CITEALP, 
967         CITEAUTHOR, CITEYEAR, CITEYEARPAR, NOCITE };
968
969 unsigned int const nCiteStyles =
970                 sizeof(citeStylesArray) / sizeof(CiteStyle);
971
972 CiteStyle const citeStylesFull[] = {
973         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
974
975 unsigned int const nCiteStylesFull =
976                 sizeof(citeStylesFull) / sizeof(CiteStyle);
977
978 CiteStyle const citeStylesUCase[] = {
979         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
980
981 unsigned int const nCiteStylesUCase =
982         sizeof(citeStylesUCase) / sizeof(CiteStyle);
983
984 } // namespace anon
985
986
987 CitationStyle citationStyleFromString(string const & command)
988 {
989         CitationStyle s;
990         if (command.empty())
991                 return s;
992
993         string cmd = command;
994         if (cmd[0] == 'C') {
995                 s.forceUpperCase = true;
996                 cmd[0] = 'c';
997         }
998
999         size_t const n = cmd.size() - 1;
1000         if (cmd != "cite" && cmd[n] == '*') {
1001                 s.full = true;
1002                 cmd = cmd.substr(0, n);
1003         }
1004
1005         char const * const * const last = citeCommands + nCiteCommands;
1006         char const * const * const ptr = find(citeCommands, last, cmd);
1007
1008         if (ptr != last) {
1009                 size_t idx = ptr - citeCommands;
1010                 s.style = citeStylesArray[idx];
1011         }
1012         return s;
1013 }
1014
1015
1016 string citationStyleToString(const CitationStyle & s)
1017 {
1018         string cite = citeCommands[s.style];
1019         if (s.full) {
1020                 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
1021                 if (std::find(citeStylesFull, last, s.style) != last)
1022                         cite += '*';
1023         }
1024
1025         if (s.forceUpperCase) {
1026                 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
1027                 if (std::find(citeStylesUCase, last, s.style) != last)
1028                         cite[0] = 'C';
1029         }
1030
1031         return cite;
1032 }
1033
1034 vector<CiteStyle> citeStyles(CiteEngine engine)
1035 {
1036         unsigned int nStyles = 0;
1037         unsigned int start = 0;
1038
1039         switch (engine) {
1040                 case ENGINE_BASIC:
1041                         nStyles = 2;
1042                         start = 0;
1043                         break;
1044                 case ENGINE_NATBIB_AUTHORYEAR:
1045                 case ENGINE_NATBIB_NUMERICAL:
1046                         nStyles = nCiteStyles - 1;
1047                         start = 1;
1048                         break;
1049                 case ENGINE_JURABIB:
1050                         nStyles = nCiteStyles;
1051                         start = 0;
1052                         break;
1053         }
1054
1055         vector<CiteStyle> styles(nStyles);
1056         size_t i = 0;
1057         int j = start;
1058         for (; i != styles.size(); ++i, ++j)
1059                 styles[i] = citeStylesArray[j];
1060
1061         return styles;
1062 }
1063
1064 } // namespace lyx
1065