]> git.lyx.org Git - lyx.git/blob - src/BiblioInfo.cpp
cmake: simplify cmake-gui usage for GNUWIN32
[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 // these are used in the expandFormat() routine, etc.
199
200 static string const pp_text   = N_("pp.");
201 static string const ed_text   = N_("ed.");
202 static string const edby_text = N_("ed. by");
203
204 } // anon namespace
205
206
207 //////////////////////////////////////////////////////////////////////
208 //
209 // BibTeXInfo
210 //
211 //////////////////////////////////////////////////////////////////////
212
213 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
214         : is_bibtex_(true), bib_key_(key), entry_type_(type), info_(),
215           modifier_(0)
216 {}
217
218
219 docstring const BibTeXInfo::getAbbreviatedAuthor() const
220 {
221         if (!is_bibtex_) {
222                 docstring const opt = label();
223                 if (opt.empty())
224                         return docstring();
225
226                 docstring authors;
227                 docstring const remainder = trim(split(opt, authors, '('));
228                 if (remainder.empty())
229                         // in this case, we didn't find a "(", 
230                         // so we don't have author (year)
231                         return docstring();
232                 return authors;
233         }
234
235         docstring author = convertLaTeXCommands(operator[]("author"));
236         if (author.empty()) {
237                 author = convertLaTeXCommands(operator[]("editor"));
238                 if (author.empty())
239                         return bib_key_;
240         }
241
242         // FIXME Move this to a separate routine that can
243         // be called from elsewhere.
244         // 
245         // OK, we've got some names. Let's format them.
246         // Try to split the author list on " and "
247         vector<docstring> const authors =
248                 getVectorFromString(author, from_ascii(" and "));
249
250         if (authors.size() == 2)
251                 return bformat(_("%1$s and %2$s"),
252                         familyName(authors[0]), familyName(authors[1]));
253
254         if (authors.size() > 2)
255                 return bformat(_("%1$s et al."), familyName(authors[0]));
256
257         return familyName(authors[0]);
258 }
259
260
261 docstring const BibTeXInfo::getYear() const
262 {
263         if (is_bibtex_) 
264                 return operator[]("year");
265
266         docstring const opt = label();
267         if (opt.empty())
268                 return docstring();
269
270         docstring authors;
271         docstring tmp = split(opt, authors, '(');
272         if (tmp.empty()) 
273                 // we don't have author (year)
274                 return docstring();
275         docstring year;
276         tmp = split(tmp, year, ')');
277         return year;
278 }
279
280
281 docstring const BibTeXInfo::getXRef() const
282 {
283         if (!is_bibtex_)
284                 return docstring();
285         return operator[]("crossref");
286 }
287
288
289 namespace {
290         string parseOptions(string const & format, string & optkey, 
291                         string & ifpart, string & elsepart);
292
293         // Calls parseOptions to deal with an embedded option, such as:
294         //   {%number%[[, no.~%number%]]}
295         // which must appear at the start of format. ifelsepart gets the
296         // whole of the option, and we return what's left after the option.
297         // we return format if there is an error.
298         string parseEmbeddedOption(string const & format, string & ifelsepart)
299         {
300                 LASSERT(format[0] == '{' && format[1] == '%', return format);
301                 string optkey;
302                 string ifpart;
303                 string elsepart;
304                 string const rest = parseOptions(format, optkey, ifpart, elsepart);
305                 if (format == rest) { // parse error
306                         LYXERR0("ERROR! Couldn't parse `" << format <<"'.");
307                         return format;
308                 }
309                 LASSERT(rest.size() <= format.size(), /* */);
310                 ifelsepart = format.substr(0, format.size() - rest.size());
311                 return rest;
312         }
313         
314         
315         // Gets a "clause" from a format string, where the clause is 
316         // delimited by '[[' and ']]'. Returns what is left after the
317         // clause is removed, and returns format if there is an error.
318         string getClause(string const & format, string & clause)
319         {
320                 string fmt = format;
321                 // remove '[['
322                 fmt = fmt.substr(2);
323                 // we'll remove characters from the front of fmt as we 
324                 // deal with them
325                 while (fmt.size()) { 
326                         if (fmt[0] == ']' && fmt.size() > 1 && fmt[1] == ']') {
327                                 // that's the end
328                                 fmt = fmt.substr(2);
329                                 break;
330                         }
331                         // check for an embedded option
332                         if (fmt[0] == '{' && fmt.size() > 1 && fmt[1] == '%') {
333                                 string part;
334                                 string const rest = parseEmbeddedOption(fmt, part);
335                                 if (fmt == rest) {
336                                         LYXERR0("ERROR! Couldn't parse embedded option in `" << format <<"'.");
337                                         return format;
338                                 }
339                                 clause += part;
340                                 fmt = rest;
341                         } else { // it's just a normal character
342                                 clause += fmt[0];
343                                 fmt = fmt.substr(1);
344                         }
345                 }
346                 return fmt;
347         }
348
349
350         // parse an options string, which must appear at the start of the
351         // format parameter. puts the parsed bits in optkey, ifpart, and
352         // elsepart and returns what's left after the option is removed.
353         // if there's an error, it returns format itself.
354         string parseOptions(string const & format, string & optkey, 
355                         string & ifpart, string & elsepart) 
356         {
357                 LASSERT(format[0] == '{' && format[1] == '%', return format);
358                 // strip '{%'
359                 string fmt = format.substr(2);
360                 size_t pos = fmt.find('%'); // end of key
361                 if (pos == string::npos) {
362                         LYXERR0("Error parsing  `" << format <<"'. Can't find end of key.");
363                         return format;
364                 }
365                 optkey = fmt.substr(0,pos);
366                 fmt = fmt.substr(pos + 1);
367                 // [[format]] should be next
368                 if (fmt[0] != '[' || fmt[1] != '[') {
369                         LYXERR0("Error parsing  `" << format <<"'. Can't find '[[' after key.");
370                         return format;
371                 }
372
373                 string curfmt = fmt;
374                 fmt = getClause(curfmt, ifpart);
375                 if (fmt == curfmt) {
376                         LYXERR0("Error parsing  `" << format <<"'. Couldn't get if clause.");
377                         return format;
378                 }
379
380                 if (fmt[0] == '}') // we're done, no else clause
381                         return fmt.substr(1);
382         
383                 // else part should follow
384                 if (fmt[0] != '[' || fmt[1] != '[') {
385                         LYXERR0("Error parsing  `" << format <<"'. Can't find else clause.");
386                         return format;
387                 }
388                 
389                 curfmt = fmt;
390                 fmt = getClause(curfmt, elsepart);
391                 // we should be done
392                 if (fmt == curfmt || fmt[0] != '}') {
393                         LYXERR0("Error parsing  `" << format <<"'. Can't find end of option.");
394                         return format;
395                 }
396                 return fmt.substr(1);
397 }
398
399 } // anon namespace
400
401
402 docstring BibTeXInfo::expandFormat(string const & format, 
403                 BibTeXInfo const * const xref, bool richtext) const
404 {
405         docstring ret; // return value
406         string key;
407         bool scanning_key = false;
408         bool scanning_rich = false;
409
410         string fmt = format;
411         // we'll remove characters from the front of fmt as we 
412         // deal with them
413         while (fmt.size()) {
414                 char_type thischar = fmt[0];
415                 if (thischar == '%') { 
416                         // beginning or end of key
417                         if (scanning_key) { 
418                                 // end of key
419                                 scanning_key = false;
420                                 // so we replace the key with its value, which may be empty
421                                 if (key == "pp_text")
422                                         ret += _(pp_text);
423                                 else if (key == "ed_text")
424                                         ret += _(ed_text);
425                                 else if(key == "edby_text")
426                                         ret += _(edby_text);
427                                 else {
428                                         docstring const val = getValueForKey(key, xref);
429                                         ret += val;
430                                 }
431                                 key.clear();
432                         } else {
433                                 // beginning of key
434                                 scanning_key = true;
435                         }
436                 } 
437                 else if (thischar == '{') { 
438                         // beginning of option?
439                         if (scanning_key) {
440                                 LYXERR0("ERROR: Found `{' when scanning key in `" << format << "'.");
441                                 return _("ERROR!");
442                         }
443                         if (fmt.size() > 1) {
444                                 if (fmt[1] == '%') {
445                                         // it is the beginning of an optional format
446                                         string optkey;
447                                         string ifpart;
448                                         string elsepart;
449                                         string const newfmt = 
450                                                 parseOptions(fmt, optkey, ifpart, elsepart);
451                                         if (newfmt == fmt) // parse error
452                                                 return _("ERROR!");
453                                         fmt = newfmt;
454                                         docstring const val = getValueForKey(optkey, xref);
455                                         if (!val.empty())
456                                                 ret += expandFormat(ifpart, xref, richtext);
457                                         else if (!elsepart.empty())
458                                                 ret += expandFormat(elsepart, xref, richtext);
459                                         // fmt will have been shortened for us already
460                                         continue; 
461                                 }
462                                 if (fmt[1] == '!') {
463                                         // beginning of rich text
464                                         scanning_rich = true;
465                                         fmt = fmt.substr(2);
466                                         continue;
467                                 }
468                         }
469                         // we are here if the '{' was at the end of the format. hmm.
470                         ret += thischar;
471                 }
472                 else if (scanning_rich && thischar == '!' 
473                          && fmt.size() > 1 && fmt[1] == '}') {
474                         // end of rich text
475                         scanning_rich = false;
476                         fmt = fmt.substr(2);
477                         continue;
478                 }
479                 else if (scanning_key)
480                         key += thischar;
481                 else if (richtext || !scanning_rich)
482                         ret += thischar;
483                 // else the character is discarded, which will happen only if
484                 // richtext == false and we are scanning rich text
485                 fmt = fmt.substr(1);
486         } // for loop
487         if (scanning_key) {
488                 LYXERR0("Never found end of key in `" << format << "'!");
489                 return _("ERROR!");
490         }
491         if (scanning_rich) {
492                 LYXERR0("Never found end of rich text in `" << format << "'!");
493                 return _("ERROR!");
494         }
495         return ret;
496 }
497
498
499 namespace {
500
501 // FIXME These would be better read from a file, so that they
502 // could be customized.
503
504         static string articleFormat = "%author%, \"%title%\", {!<i>!}%journal%{!</i>!} {%volume%[[ %volume%{%number%[[, %number%]]}]]} (%year%){%pages%[[, %pp_text% %pages%]]}.{%note%[[ %note%]]}";
505
506         static string bookFormat = "{%author%[[%author%]][[%editor%, %ed_text%]]}, {!<i>!}%title%{!</i>!}{%volume%[[ vol. %volume%]][[{%number%[[no. %number%]]}]]}{%edition%[[%edition%]]} ({%address%[[%address%: ]]}%publisher%, %year%).{%note%[[ %note%]]}";
507
508         static string inSomething = "%author%, \"%title%\", in{%editor%[[ %editor%, %ed_text%,]]} {!<i>!}%booktitle%{!</i>!}{%volume%[[ vol. %volume%]][[{%number%[[no. %number%]]}]]}{%edition%[[%edition%]]} ({%address%[[%address%: ]]}%publisher%, %year%){%pages%[[, %pp_text% %pages%]]}.{%note%[[ %note%]]}";
509
510         static string thesis = "%author%, %title% ({%address%[[%address%: ]]}%school%, %year%).{%note%[[ %note%]]}";
511
512         static string defaultFormat = "{%author%[[%author%, ]][[{%editor%[[%editor%, %ed_text%, ]]}]]}\"%title%\"{%journal%[[, {!<i>!}%journal%{!</i>!}]][[{%publisher%[[, %publisher%]][[{%institution%[[, %institution%]]}]]}]]}{%year%[[ (%year%)]]}{%pages%[[, %pages%]]}.";
513
514 }
515
516 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref,
517         bool richtext) const
518 {
519         if (!info_.empty())
520                 return info_;
521
522         if (!is_bibtex_) {
523                 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
524                 info_ = it->second;
525                 return info_;
526         }
527
528         if (entry_type_ == "article")
529                 info_ = expandFormat(articleFormat, xref, richtext);
530         else if (entry_type_ == "book")
531                 info_ = expandFormat(bookFormat, xref, richtext);
532         else if (entry_type_.substr(0,2) == "in")
533                 info_ = expandFormat(inSomething, xref, richtext);
534         else if (entry_type_ == "phdthesis" || entry_type_ == "mastersthesis")
535                 info_ = expandFormat(thesis, xref, richtext);
536         else 
537                 info_ = expandFormat(defaultFormat, xref, richtext);
538
539         if (!info_.empty())
540                 info_ = convertLaTeXCommands(info_);
541         return info_;
542 }
543
544
545 docstring const & BibTeXInfo::operator[](docstring const & field) const
546 {
547         BibTeXInfo::const_iterator it = find(field);
548         if (it != end())
549                 return it->second;
550         static docstring const empty_value = docstring();
551         return empty_value;
552 }
553         
554         
555 docstring const & BibTeXInfo::operator[](string const & field) const
556 {
557         return operator[](from_ascii(field));
558 }
559
560
561 docstring BibTeXInfo::getValueForKey(string const & key, 
562                 BibTeXInfo const * const xref) const
563 {
564         docstring const ret = operator[](key);
565         if (!ret.empty() || !xref)
566                 return ret;
567         return (*xref)[key];
568 }
569
570
571 //////////////////////////////////////////////////////////////////////
572 //
573 // BiblioInfo
574 //
575 //////////////////////////////////////////////////////////////////////
576
577 namespace {
578 // A functor for use with sort, leading to case insensitive sorting
579         class compareNoCase: public binary_function<docstring, docstring, bool>
580         {
581                 public:
582                         bool operator()(docstring const & s1, docstring const & s2) const {
583                                 return compare_no_case(s1, s2) < 0;
584                         }
585         };
586 } // namespace anon
587
588
589 vector<docstring> const BiblioInfo::getKeys() const
590 {
591         vector<docstring> bibkeys;
592         BiblioInfo::const_iterator it  = begin();
593         for (; it != end(); ++it)
594                 bibkeys.push_back(it->first);
595         sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
596         return bibkeys;
597 }
598
599
600 vector<docstring> const BiblioInfo::getFields() const
601 {
602         vector<docstring> bibfields;
603         set<docstring>::const_iterator it = field_names_.begin();
604         set<docstring>::const_iterator end = field_names_.end();
605         for (; it != end; ++it)
606                 bibfields.push_back(*it);
607         sort(bibfields.begin(), bibfields.end());
608         return bibfields;
609 }
610
611
612 vector<docstring> const BiblioInfo::getEntries() const
613 {
614         vector<docstring> bibentries;
615         set<docstring>::const_iterator it = entry_types_.begin();
616         set<docstring>::const_iterator end = entry_types_.end();
617         for (; it != end; ++it)
618                 bibentries.push_back(*it);
619         sort(bibentries.begin(), bibentries.end());
620         return bibentries;
621 }
622
623
624 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
625 {
626         BiblioInfo::const_iterator it = find(key);
627         if (it == end())
628                 return docstring();
629         BibTeXInfo const & data = it->second;
630         return data.getAbbreviatedAuthor();
631 }
632
633
634 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
635 {
636         BiblioInfo::const_iterator it = find(key);
637         if (it == end())
638                 return docstring();
639         BibTeXInfo const & data = it->second;
640         return data.citeNumber();
641 }
642
643
644 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier) const
645 {
646         BiblioInfo::const_iterator it = find(key);
647         if (it == end())
648                 return docstring();
649         BibTeXInfo const & data = it->second;
650         docstring year = data.getYear();
651         if (year.empty()) {
652                 // let's try the crossref
653                 docstring const xref = data.getXRef();
654                 if (xref.empty())
655                         return _("No year"); // no luck
656                 BiblioInfo::const_iterator const xrefit = find(xref);
657                 if (xrefit == end())
658                         return _("No year"); // no luck again
659                 BibTeXInfo const & xref_data = xrefit->second;
660                 year = xref_data.getYear();
661         }
662         if (use_modifier && data.modifier() != 0)
663                 year += data.modifier();
664         return year;
665 }
666
667
668 docstring const BiblioInfo::getInfo(docstring const & key, bool richtext) const
669 {
670         BiblioInfo::const_iterator it = find(key);
671         if (it == end())
672                 return docstring();
673         BibTeXInfo const & data = it->second;
674         BibTeXInfo const * xrefptr = 0;
675         docstring const xref = data.getXRef();
676         if (!xref.empty()) {
677                 BiblioInfo::const_iterator const xrefit = find(xref);
678                 if (xrefit != end())
679                         xrefptr = &(xrefit->second);
680         }
681         return data.getInfo(xrefptr, richtext);
682 }
683
684
685 bool BiblioInfo::isBibtex(docstring const & key) const
686 {
687         BiblioInfo::const_iterator it = find(key);
688         if (it == end())
689                 return false;
690         return it->second.isBibTeX();
691 }
692
693
694
695 vector<docstring> const BiblioInfo::getCiteStrings(
696         docstring const & key, Buffer const & buf) const
697 {
698         CiteEngine const engine = buf.params().citeEngine();
699         if (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL)
700                 return getNumericalStrings(key, buf);
701         else
702                 return getAuthorYearStrings(key, buf);
703 }
704
705
706 vector<docstring> const BiblioInfo::getNumericalStrings(
707         docstring const & key, Buffer const & buf) const
708 {
709         if (empty())
710                 return vector<docstring>();
711
712         docstring const author = getAbbreviatedAuthor(key);
713         docstring const year   = getYear(key);
714         if (author.empty() || year.empty())
715                 return vector<docstring>();
716
717         vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
718         
719         vector<docstring> vec(styles.size());
720         for (size_t i = 0; i != vec.size(); ++i) {
721                 docstring str;
722
723                 switch (styles[i]) {
724                         case CITE:
725                         case CITEP:
726                                 str = from_ascii("[#ID]");
727                                 break;
728
729                         case NOCITE:
730                                 str = _("Add to bibliography only.");
731                                 break;
732
733                         case CITET:
734                                 str = author + " [#ID]";
735                                 break;
736
737                         case CITEALT:
738                                 str = author + " #ID";
739                                 break;
740
741                         case CITEALP:
742                                 str = from_ascii("#ID");
743                                 break;
744
745                         case CITEAUTHOR:
746                                 str = author;
747                                 break;
748
749                         case CITEYEAR:
750                                 str = year;
751                                 break;
752
753                         case CITEYEARPAR:
754                                 str = '(' + year + ')';
755                                 break;
756                 }
757
758                 vec[i] = str;
759         }
760
761         return vec;
762 }
763
764
765 vector<docstring> const BiblioInfo::getAuthorYearStrings(
766         docstring const & key, Buffer const & buf) const
767 {
768         if (empty())
769                 return vector<docstring>();
770
771         docstring const author = getAbbreviatedAuthor(key);
772         docstring const year   = getYear(key);
773         if (author.empty() || year.empty())
774                 return vector<docstring>();
775
776         vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
777         
778         vector<docstring> vec(styles.size());
779         for (size_t i = 0; i != vec.size(); ++i) {
780                 docstring str;
781
782                 switch (styles[i]) {
783                         case CITE:
784                 // jurabib only: Author/Annotator
785                 // (i.e. the "before" field, 2nd opt arg)
786                                 str = author + "/<" + _("before") + '>';
787                                 break;
788
789                         case NOCITE:
790                                 str = _("Add to bibliography only.");
791                                 break;
792
793                         case CITET:
794                                 str = author + " (" + year + ')';
795                                 break;
796
797                         case CITEP:
798                                 str = '(' + author + ", " + year + ')';
799                                 break;
800
801                         case CITEALT:
802                                 str = author + ' ' + year ;
803                                 break;
804
805                         case CITEALP:
806                                 str = author + ", " + year ;
807                                 break;
808
809                         case CITEAUTHOR:
810                                 str = author;
811                                 break;
812
813                         case CITEYEAR:
814                                 str = year;
815                                 break;
816
817                         case CITEYEARPAR:
818                                 str = '(' + year + ')';
819                                 break;
820                 }
821                 vec[i] = str;
822         }
823         return vec;
824 }
825
826
827 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
828 {
829         bimap_.insert(info.begin(), info.end());
830 }
831
832
833 namespace {
834         // used in xhtml to sort a list of BibTeXInfo objects
835         bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
836         {
837                 docstring const lauth = lhs->getAbbreviatedAuthor();
838                 docstring const rauth = rhs->getAbbreviatedAuthor();
839                 docstring const lyear = lhs->getYear();
840                 docstring const ryear = rhs->getYear();
841                 docstring const ltitl = lhs->operator[]("title");
842                 docstring const rtitl = rhs->operator[]("title");
843                 return  (lauth < rauth)
844                                 || (lauth == rauth && lyear < ryear)
845                                 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
846         }
847 }
848
849
850 void BiblioInfo::collectCitedEntries(Buffer const & buf)
851 {
852         cited_entries_.clear();
853         // We are going to collect all the citation keys used in the document,
854         // getting them from the TOC.
855         // FIXME We may want to collect these differently, in the first case,
856         // so that we might have them in order of appearance.
857         set<docstring> citekeys;
858         Toc const & toc = buf.tocBackend().toc("citation");
859         Toc::const_iterator it = toc.begin();
860         Toc::const_iterator const en = toc.end();
861         for (; it != en; ++it) {
862                 if (it->str().empty())
863                         continue;
864                 vector<docstring> const keys = getVectorFromString(it->str());
865                 citekeys.insert(keys.begin(), keys.end());
866         }
867         if (citekeys.empty())
868                 return;
869         
870         // We have a set of the keys used in this document.
871         // We will now convert it to a list of the BibTeXInfo objects used in 
872         // this document...
873         vector<BibTeXInfo const *> bi;
874         set<docstring>::const_iterator cit = citekeys.begin();
875         set<docstring>::const_iterator const cen = citekeys.end();
876         for (; cit != cen; ++cit) {
877                 BiblioInfo::const_iterator const bt = find(*cit);
878                 if (bt == end() || !bt->second.isBibTeX())
879                         continue;
880                 bi.push_back(&(bt->second));
881         }
882         // ...and sort it.
883         sort(bi.begin(), bi.end(), lSorter);
884         
885         // Now we can write the sorted keys
886         vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
887         vector<BibTeXInfo const *>::const_iterator ben = bi.end();
888         for (; bit != ben; ++bit)
889                 cited_entries_.push_back((*bit)->key());
890 }
891
892
893 void BiblioInfo::makeCitationLabels(Buffer const & buf)
894 {
895         collectCitedEntries(buf);
896         CiteEngine const engine = buf.params().citeEngine();
897         bool const numbers = 
898                 (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL);
899
900         int keynumber = 0;
901         char modifier = 0;
902         // used to remember the last one we saw
903         // we'll be comparing entries to see if we need to add
904         // modifiers, like "1984a"
905         map<docstring, BibTeXInfo>::iterator last;
906
907         vector<docstring>::const_iterator it = cited_entries_.begin();
908         vector<docstring>::const_iterator const en = cited_entries_.end();
909         for (; it != en; ++it) {
910                 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
911                 // this shouldn't happen, but...
912                 if (biit == bimap_.end())
913                         // ...fail gracefully, anyway.
914                         continue;
915                 BibTeXInfo & entry = biit->second;
916                 if (numbers) {
917                         docstring const num = convert<docstring>(++keynumber);
918                         entry.setCiteNumber(num);
919                 } else {
920                         if (it != cited_entries_.begin()
921                             && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
922                             // we access the year via getYear() so as to get it from the xref,
923                             // if we need to do so
924                             && getYear(entry.key()) == getYear(last->second.key())) {
925                                 if (modifier == 0) {
926                                         // so the last one should have been 'a'
927                                         last->second.setModifier('a');
928                                         modifier = 'b';
929                                 } else if (modifier == 'z')
930                                         modifier = 'A';
931                                 else
932                                         modifier++;
933                         } else {
934                                 modifier = 0;
935                         }
936                         entry.setModifier(modifier);                            
937                         // remember the last one
938                         last = biit;
939                 }
940         }
941 }
942
943
944 //////////////////////////////////////////////////////////////////////
945 //
946 // CitationStyle
947 //
948 //////////////////////////////////////////////////////////////////////
949
950 namespace {
951
952
953 char const * const citeCommands[] = {
954         "cite", "citet", "citep", "citealt", "citealp",
955         "citeauthor", "citeyear", "citeyearpar", "nocite" };
956
957 unsigned int const nCiteCommands =
958                 sizeof(citeCommands) / sizeof(char *);
959
960 CiteStyle const citeStylesArray[] = {
961         CITE, CITET, CITEP, CITEALT, CITEALP, 
962         CITEAUTHOR, CITEYEAR, CITEYEARPAR, NOCITE };
963
964 unsigned int const nCiteStyles =
965                 sizeof(citeStylesArray) / sizeof(CiteStyle);
966
967 CiteStyle const citeStylesFull[] = {
968         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
969
970 unsigned int const nCiteStylesFull =
971                 sizeof(citeStylesFull) / sizeof(CiteStyle);
972
973 CiteStyle const citeStylesUCase[] = {
974         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
975
976 unsigned int const nCiteStylesUCase =
977         sizeof(citeStylesUCase) / sizeof(CiteStyle);
978
979 } // namespace anon
980
981
982 CitationStyle citationStyleFromString(string const & command)
983 {
984         CitationStyle s;
985         if (command.empty())
986                 return s;
987
988         string cmd = command;
989         if (cmd[0] == 'C') {
990                 s.forceUpperCase = true;
991                 cmd[0] = 'c';
992         }
993
994         size_t const n = cmd.size() - 1;
995         if (cmd != "cite" && cmd[n] == '*') {
996                 s.full = true;
997                 cmd = cmd.substr(0, n);
998         }
999
1000         char const * const * const last = citeCommands + nCiteCommands;
1001         char const * const * const ptr = find(citeCommands, last, cmd);
1002
1003         if (ptr != last) {
1004                 size_t idx = ptr - citeCommands;
1005                 s.style = citeStylesArray[idx];
1006         }
1007         return s;
1008 }
1009
1010
1011 string citationStyleToString(const CitationStyle & s)
1012 {
1013         string cite = citeCommands[s.style];
1014         if (s.full) {
1015                 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
1016                 if (std::find(citeStylesFull, last, s.style) != last)
1017                         cite += '*';
1018         }
1019
1020         if (s.forceUpperCase) {
1021                 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
1022                 if (std::find(citeStylesUCase, last, s.style) != last)
1023                         cite[0] = 'C';
1024         }
1025
1026         return cite;
1027 }
1028
1029 vector<CiteStyle> citeStyles(CiteEngine engine)
1030 {
1031         unsigned int nStyles = 0;
1032         unsigned int start = 0;
1033
1034         switch (engine) {
1035                 case ENGINE_BASIC:
1036                         nStyles = 2;
1037                         start = 0;
1038                         break;
1039                 case ENGINE_NATBIB_AUTHORYEAR:
1040                 case ENGINE_NATBIB_NUMERICAL:
1041                         nStyles = nCiteStyles - 1;
1042                         start = 1;
1043                         break;
1044                 case ENGINE_JURABIB:
1045                         nStyles = nCiteStyles;
1046                         start = 0;
1047                         break;
1048         }
1049
1050         vector<CiteStyle> styles(nStyles);
1051         size_t i = 0;
1052         int j = start;
1053         for (; i != styles.size(); ++i, ++j)
1054                 styles[i] = citeStylesArray[j];
1055
1056         return styles;
1057 }
1058
1059 } // namespace lyx
1060