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