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