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