]> git.lyx.org Git - features.git/blob - src/BiblioInfo.cpp
Introduce a simple macro facility for citation formats. Also introduce
[features.git] / src / BiblioInfo.cpp
1 /**
2  * \file BiblioInfo.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  * \author Herbert Voß
8  * \author Richard Heck
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "BiblioInfo.h"
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "buffer_funcs.h"
19 #include "Encoding.h"
20 #include "InsetIterator.h"
21 #include "Paragraph.h"
22 #include "TextClass.h"
23 #include "TocBackend.h"
24
25 #include "insets/Inset.h"
26 #include "insets/InsetBibitem.h"
27 #include "insets/InsetBibtex.h"
28 #include "insets/InsetInclude.h"
29
30 #include "support/convert.h"
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/gettext.h"
34 #include "support/lassert.h"
35 #include "support/lstrings.h"
36 #include "support/textutils.h"
37
38 #include "boost/regex.hpp"
39
40 #include <set>
41
42 using namespace std;
43 using namespace lyx::support;
44
45
46 namespace lyx {
47
48 namespace {
49
50 // gets the "family name" from an author-type string
51 docstring familyName(docstring const & name)
52 {
53         if (name.empty())
54                 return docstring();
55
56         // first we look for a comma, and take the last name to be everything
57         // preceding the right-most one, so that we also get the "jr" part.
58         docstring::size_type idx = name.rfind(',');
59         if (idx != docstring::npos)
60                 return ltrim(name.substr(0, idx));
61
62         // OK, so now we want to look for the last name. We're going to
63         // include the "von" part. This isn't perfect.
64         // Split on spaces, to get various tokens.
65         vector<docstring> pieces = getVectorFromString(name, from_ascii(" "));
66         // If we only get two, assume the last one is the last name
67         if (pieces.size() <= 2)
68                 return pieces.back();
69
70         // Now we look for the first token that begins with a lower case letter.
71         vector<docstring>::const_iterator it = pieces.begin();
72         vector<docstring>::const_iterator en = pieces.end();
73         for (; it != en; ++it) {
74                 if ((*it).size() == 0)
75                         continue;
76                 char_type const c = (*it)[0];
77                 if (isLower(c))
78                         break;
79         }
80
81         if (it == en) // we never found a "von"
82                 return pieces.back();
83
84         // reconstruct what we need to return
85         docstring retval;
86         bool first = true;
87         for (; it != en; ++it) {
88                 if (!first)
89                         retval += " ";
90                 else 
91                         first = false;
92                 retval += *it;
93         }
94         return retval;
95 }
96
97 // converts a string containing LaTeX commands into unicode
98 // for display.
99 docstring convertLaTeXCommands(docstring const & str)
100 {
101         docstring val = str;
102         docstring ret;
103
104         bool scanning_cmd = false;
105         bool scanning_math = false;
106         bool escaped = false; // used to catch \$, etc.
107         while (val.size()) {
108                 char_type const ch = val[0];
109
110                 // if we're scanning math, we output everything until we
111                 // find an unescaped $, at which point we break out.
112                 if (scanning_math) {
113                         if (escaped)
114                                 escaped = false;
115                         else if (ch == '\\')
116                                 escaped = true;
117                         else if (ch == '$') 
118                                 scanning_math = false;
119                         ret += ch;
120                         val = val.substr(1);
121                         continue;
122                 }
123
124                 // if we're scanning a command name, then we just
125                 // discard characters until we hit something that
126                 // isn't alpha.
127                 if (scanning_cmd) {
128                         if (isAlphaASCII(ch)) {
129                                 val = val.substr(1);
130                                 escaped = false;
131                                 continue;
132                         }
133                         // so we're done with this command.
134                         // now we fall through and check this character.
135                         scanning_cmd = false;
136                 }
137
138                 // was the last character a \? If so, then this is something like:
139                 // \\ or \$, so we'll just output it. That's probably not always right...
140                 if (escaped) {
141                         // exception: output \, as THIN SPACE
142                         if (ch == ',')
143                                 ret.push_back(0x2009);
144                         else
145                                 ret += ch;
146                         val = val.substr(1);
147                         escaped = false;
148                         continue;
149                 }
150
151                 if (ch == '$') {
152                         ret += ch;
153                         val = val.substr(1);
154                         scanning_math = true;
155                         continue;
156                 }
157
158                 // we just ignore braces
159                 if (ch == '{' || ch == '}') {
160                         val = val.substr(1);
161                         continue;
162                 }
163
164                 // we're going to check things that look like commands, so if
165                 // this doesn't, just output it.
166                 if (ch != '\\') {
167                         ret += ch;
168                         val = val.substr(1);
169                         continue;
170                 }
171
172                 // ok, could be a command of some sort
173                 // let's see if it corresponds to some unicode
174                 // unicodesymbols has things in the form: \"{u},
175                 // whereas we may see things like: \"u. So we'll
176                 // look for that and change it, if necessary.
177                 static boost::regex const reg("^\\\\\\W\\w");
178                 if (boost::regex_search(to_utf8(val), reg)) {
179                         val.insert(3, from_ascii("}"));
180                         val.insert(2, from_ascii("{"));
181                 }
182                 docstring rem;
183                 docstring const cnvtd = Encodings::fromLaTeXCommand(val, rem,
184                                                         Encodings::TEXT_CMD);
185                 if (!cnvtd.empty()) {
186                         // it did, so we'll take that bit and proceed with what's left
187                         ret += cnvtd;
188                         val = rem;
189                         continue;
190                 }
191                 // it's a command of some sort
192                 scanning_cmd = true;
193                 escaped = true;
194                 val = val.substr(1);
195         }
196         return ret;
197 }
198
199 } // anon namespace
200
201
202 //////////////////////////////////////////////////////////////////////
203 //
204 // BibTeXInfo
205 //
206 //////////////////////////////////////////////////////////////////////
207
208 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
209         : is_bibtex_(true), bib_key_(key), entry_type_(type), info_(),
210           modifier_(0)
211 {}
212
213
214 docstring const BibTeXInfo::getAbbreviatedAuthor() const
215 {
216         if (!is_bibtex_) {
217                 docstring const opt = label();
218                 if (opt.empty())
219                         return docstring();
220
221                 docstring authors;
222                 docstring const remainder = trim(split(opt, authors, '('));
223                 if (remainder.empty())
224                         // in this case, we didn't find a "(", 
225                         // so we don't have author (year)
226                         return docstring();
227                 return authors;
228         }
229
230         docstring author = convertLaTeXCommands(operator[]("author"));
231         if (author.empty()) {
232                 author = convertLaTeXCommands(operator[]("editor"));
233                 if (author.empty())
234                         return bib_key_;
235         }
236
237         // FIXME Move this to a separate routine that can
238         // be called from elsewhere.
239         // 
240         // OK, we've got some names. Let's format them.
241         // Try to split the author list on " and "
242         vector<docstring> const authors =
243                 getVectorFromString(author, from_ascii(" and "));
244
245         if (authors.size() == 2)
246                 return bformat(_("%1$s and %2$s"),
247                         familyName(authors[0]), familyName(authors[1]));
248
249         if (authors.size() > 2)
250                 return bformat(_("%1$s et al."), familyName(authors[0]));
251
252         return familyName(authors[0]);
253 }
254
255
256 docstring const BibTeXInfo::getYear() const
257 {
258         if (is_bibtex_) 
259                 return operator[]("year");
260
261         docstring const opt = label();
262         if (opt.empty())
263                 return docstring();
264
265         docstring authors;
266         docstring tmp = split(opt, authors, '(');
267         if (tmp.empty()) 
268                 // we don't have author (year)
269                 return docstring();
270         docstring year;
271         tmp = split(tmp, year, ')');
272         return year;
273 }
274
275
276 docstring const BibTeXInfo::getXRef() const
277 {
278         if (!is_bibtex_)
279                 return docstring();
280         return operator[]("crossref");
281 }
282
283
284 namespace {
285         string parseOptions(string const & format, string & optkey, 
286                         string & ifpart, string & elsepart);
287
288         // Calls parseOptions to deal with an embedded option, such as:
289         //   {%number%[[, no.~%number%]]}
290         // which must appear at the start of format. ifelsepart gets the
291         // whole of the option, and we return what's left after the option.
292         // we return format if there is an error.
293         string parseEmbeddedOption(string const & format, string & ifelsepart)
294         {
295                 LASSERT(format[0] == '{' && format[1] == '%', return format);
296                 string optkey;
297                 string ifpart;
298                 string elsepart;
299                 string const rest = parseOptions(format, optkey, ifpart, elsepart);
300                 if (format == rest) { // parse error
301                         LYXERR0("ERROR! Couldn't parse `" << format <<"'.");
302                         return format;
303                 }
304                 LASSERT(rest.size() <= format.size(), /* */);
305                 ifelsepart = format.substr(0, format.size() - rest.size());
306                 return rest;
307         }
308         
309         
310         // Gets a "clause" from a format string, where the clause is 
311         // delimited by '[[' and ']]'. Returns what is left after the
312         // clause is removed, and returns format if there is an error.
313         string getClause(string const & format, string & clause)
314         {
315                 string fmt = format;
316                 // remove '[['
317                 fmt = fmt.substr(2);
318                 // we'll remove characters from the front of fmt as we 
319                 // deal with them
320                 while (fmt.size()) { 
321                         if (fmt[0] == ']' && fmt.size() > 1 && fmt[1] == ']') {
322                                 // that's the end
323                                 fmt = fmt.substr(2);
324                                 break;
325                         }
326                         // check for an embedded option
327                         if (fmt[0] == '{' && fmt.size() > 1 && fmt[1] == '%') {
328                                 string part;
329                                 string const rest = parseEmbeddedOption(fmt, part);
330                                 if (fmt == rest) {
331                                         LYXERR0("ERROR! Couldn't parse embedded option in `" << format <<"'.");
332                                         return format;
333                                 }
334                                 clause += part;
335                                 fmt = rest;
336                         } else { // it's just a normal character
337                                 clause += fmt[0];
338                                 fmt = fmt.substr(1);
339                         }
340                 }
341                 return fmt;
342         }
343
344
345         // parse an options string, which must appear at the start of the
346         // format parameter. puts the parsed bits in optkey, ifpart, and
347         // elsepart and returns what's left after the option is removed.
348         // if there's an error, it returns format itself.
349         string parseOptions(string const & format, string & optkey, 
350                         string & ifpart, string & elsepart) 
351         {
352                 LASSERT(format[0] == '{' && format[1] == '%', return format);
353                 // strip '{%'
354                 string fmt = format.substr(2);
355                 size_t pos = fmt.find('%'); // end of key
356                 if (pos == string::npos) {
357                         LYXERR0("Error parsing  `" << format <<"'. Can't find end of key.");
358                         return format;
359                 }
360                 optkey = fmt.substr(0,pos);
361                 fmt = fmt.substr(pos + 1);
362                 // [[format]] should be next
363                 if (fmt[0] != '[' || fmt[1] != '[') {
364                         LYXERR0("Error parsing  `" << format <<"'. Can't find '[[' after key.");
365                         return format;
366                 }
367
368                 string curfmt = fmt;
369                 fmt = getClause(curfmt, ifpart);
370                 if (fmt == curfmt) {
371                         LYXERR0("Error parsing  `" << format <<"'. Couldn't get if clause.");
372                         return format;
373                 }
374
375                 if (fmt[0] == '}') // we're done, no else clause
376                         return fmt.substr(1);
377         
378                 // else part should follow
379                 if (fmt[0] != '[' || fmt[1] != '[') {
380                         LYXERR0("Error parsing  `" << format <<"'. Can't find else clause.");
381                         return format;
382                 }
383                 
384                 curfmt = fmt;
385                 fmt = getClause(curfmt, elsepart);
386                 // we should be done
387                 if (fmt == curfmt || fmt[0] != '}') {
388                         LYXERR0("Error parsing  `" << format <<"'. Can't find end of option.");
389                         return format;
390                 }
391                 return fmt.substr(1);
392 }
393
394 } // anon namespace
395
396
397 docstring BibTeXInfo::expandFormat(string const & format, 
398                 BibTeXInfo const * const xref, Buffer const & buf, 
399                 bool richtext) const
400 {
401         // incorrect use of macros could put us in an infinite loop
402         static int max_passes = 1000;
403         docstring ret; // return value
404         string key;
405         bool scanning_key = false;
406         bool scanning_rich = false;
407
408         int passes = 0;
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 (passes++ > 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                                         ret += _(val);
437                                 } else {
438                                         docstring const val = getValueForKey(key, xref);
439                                         ret += val;
440                                 }
441                         } else {
442                                 // beginning of key
443                                 key.clear();
444                                 scanning_key = true;
445                         }
446                 }
447                 else if (thischar == '{') { 
448                         // beginning of option?
449                         if (scanning_key) {
450                                 LYXERR0("ERROR: Found `{' when scanning key in `" << format << "'.");
451                                 return _("ERROR!");
452                         }
453                         if (fmt.size() > 1) {
454                                 if (fmt[1] == '%') {
455                                         // it is the beginning of an optional format
456                                         string optkey;
457                                         string ifpart;
458                                         string elsepart;
459                                         string const newfmt = 
460                                                 parseOptions(fmt, optkey, ifpart, elsepart);
461                                         if (newfmt == fmt) // parse error
462                                                 return _("ERROR!");
463                                         fmt = newfmt;
464                                         docstring const val = getValueForKey(optkey, xref);
465                                         if (!val.empty())
466                                                 ret += expandFormat(ifpart, xref, buf, richtext);
467                                         else if (!elsepart.empty())
468                                                 ret += expandFormat(elsepart, xref, buf, richtext);
469                                         // fmt will have been shortened for us already
470                                         continue; 
471                                 }
472                                 if (fmt[1] == '!') {
473                                         // beginning of rich text
474                                         scanning_rich = true;
475                                         fmt = fmt.substr(2);
476                                         continue;
477                                 }
478                         }
479                         // we are here if '{' was not followed by % or !. 
480                         // So it's just a character.
481                         ret += thischar;
482                 }
483                 else if (scanning_rich && thischar == '!' 
484                          && fmt.size() > 1 && fmt[1] == '}') {
485                         // end of rich text
486                         scanning_rich = false;
487                         fmt = fmt.substr(2);
488                         continue;
489                 }
490                 else if (scanning_key)
491                         key += char(thischar);
492                 else if (richtext || !scanning_rich)
493                         ret += thischar;
494                 // else the character is discarded, which will happen only if
495                 // richtext == false and we are scanning rich text
496                 fmt = fmt.substr(1);
497         } // for loop
498         if (scanning_key) {
499                 LYXERR0("Never found end of key in `" << format << "'!");
500                 return _("ERROR!");
501         }
502         if (scanning_rich) {
503                 LYXERR0("Never found end of rich text in `" << format << "'!");
504                 return _("ERROR!");
505         }
506         return ret;
507 }
508
509
510 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref,
511         Buffer const & buf, bool richtext) const
512 {
513         if (!info_.empty())
514                 return info_;
515
516         if (!is_bibtex_) {
517                 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
518                 info_ = it->second;
519                 return info_;
520         }
521
522         DocumentClass const & dc = buf.params().documentClass();
523         string const & format = dc.getCiteFormat(to_utf8(entry_type_));
524         info_ = expandFormat(format, xref, buf, richtext);
525
526         if (!info_.empty())
527                 info_ = convertLaTeXCommands(info_);
528         return info_;
529 }
530
531
532 docstring const & BibTeXInfo::operator[](docstring const & field) const
533 {
534         BibTeXInfo::const_iterator it = find(field);
535         if (it != end())
536                 return it->second;
537         static docstring const empty_value = docstring();
538         return empty_value;
539 }
540         
541         
542 docstring const & BibTeXInfo::operator[](string const & field) const
543 {
544         return operator[](from_ascii(field));
545 }
546
547
548 docstring BibTeXInfo::getValueForKey(string const & key, 
549                 BibTeXInfo const * const xref) const
550 {
551         docstring const ret = operator[](key);
552         if (!ret.empty() || !xref)
553                 return ret;
554         return (*xref)[key];
555 }
556
557
558 //////////////////////////////////////////////////////////////////////
559 //
560 // BiblioInfo
561 //
562 //////////////////////////////////////////////////////////////////////
563
564 namespace {
565 // A functor for use with sort, leading to case insensitive sorting
566         class compareNoCase: public binary_function<docstring, docstring, bool>
567         {
568                 public:
569                         bool operator()(docstring const & s1, docstring const & s2) const {
570                                 return compare_no_case(s1, s2) < 0;
571                         }
572         };
573 } // namespace anon
574
575
576 vector<docstring> const BiblioInfo::getKeys() const
577 {
578         vector<docstring> bibkeys;
579         BiblioInfo::const_iterator it  = begin();
580         for (; it != end(); ++it)
581                 bibkeys.push_back(it->first);
582         sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
583         return bibkeys;
584 }
585
586
587 vector<docstring> const BiblioInfo::getFields() const
588 {
589         vector<docstring> bibfields;
590         set<docstring>::const_iterator it = field_names_.begin();
591         set<docstring>::const_iterator end = field_names_.end();
592         for (; it != end; ++it)
593                 bibfields.push_back(*it);
594         sort(bibfields.begin(), bibfields.end());
595         return bibfields;
596 }
597
598
599 vector<docstring> const BiblioInfo::getEntries() const
600 {
601         vector<docstring> bibentries;
602         set<docstring>::const_iterator it = entry_types_.begin();
603         set<docstring>::const_iterator end = entry_types_.end();
604         for (; it != end; ++it)
605                 bibentries.push_back(*it);
606         sort(bibentries.begin(), bibentries.end());
607         return bibentries;
608 }
609
610
611 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
612 {
613         BiblioInfo::const_iterator it = find(key);
614         if (it == end())
615                 return docstring();
616         BibTeXInfo const & data = it->second;
617         return data.getAbbreviatedAuthor();
618 }
619
620
621 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
622 {
623         BiblioInfo::const_iterator it = find(key);
624         if (it == end())
625                 return docstring();
626         BibTeXInfo const & data = it->second;
627         return data.citeNumber();
628 }
629
630
631 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier) const
632 {
633         BiblioInfo::const_iterator it = find(key);
634         if (it == end())
635                 return docstring();
636         BibTeXInfo const & data = it->second;
637         docstring year = data.getYear();
638         if (year.empty()) {
639                 // let's try the crossref
640                 docstring const xref = data.getXRef();
641                 if (xref.empty())
642                         return _("No year"); // no luck
643                 BiblioInfo::const_iterator const xrefit = find(xref);
644                 if (xrefit == end())
645                         return _("No year"); // no luck again
646                 BibTeXInfo const & xref_data = xrefit->second;
647                 year = xref_data.getYear();
648         }
649         if (use_modifier && data.modifier() != 0)
650                 year += data.modifier();
651         return year;
652 }
653
654
655 docstring const BiblioInfo::getInfo(docstring const & key, 
656         Buffer const & buf, 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, buf, 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