]> git.lyx.org Git - lyx.git/blob - src/BiblioInfo.cpp
dd389c509ecef4a9a8409b2683e3940b67c57c72
[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 = operator[]("author");
275         if (author.empty()) {
276                 author = 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 convertLaTeXCommands(shortauthor);
295         }
296
297         docstring retval = familyName(authors[0]);
298
299         if (authors.size() == 2 && authors[1] != "others")
300                 retval = bformat(from_ascii("%1$s and %2$s"),
301                         familyName(authors[0]), familyName(authors[1]));
302
303         if (authors.size() >= 2)
304                 retval = bformat(from_ascii("%1$s et al."),
305                         familyName(authors[0]));
306
307         return convertLaTeXCommands(retval);
308 }
309
310
311 docstring const BibTeXInfo::getAbbreviatedAuthor(Buffer const & buf, bool jurabib_style) const
312 {
313         docstring const author = getAbbreviatedAuthor(jurabib_style);
314         if (!is_bibtex_)
315                 return author;
316         vector<docstring> const authors = getVectorFromString(author, from_ascii(" and "));
317         if (authors.size() == 2)
318                 return bformat(buf.B_("%1$s and %2$s"), authors[0], authors[1]);
319         docstring::size_type const idx = author.rfind(from_ascii(" et al."));
320         if (idx != docstring::npos)
321                 return bformat(buf.B_("%1$s et al."), author.substr(0, idx));
322         return author;
323 }
324
325
326 docstring const BibTeXInfo::getYear() const
327 {
328         if (is_bibtex_)
329                 return operator[]("year");
330
331         docstring const opt = label();
332         if (opt.empty())
333                 return docstring();
334
335         docstring authors;
336         docstring tmp = split(opt, authors, '(');
337         if (tmp.empty())
338                 // we don't have author (year)
339                 return docstring();
340         docstring year;
341         tmp = split(tmp, year, ')');
342         return year;
343 }
344
345
346 docstring const BibTeXInfo::getXRef() const
347 {
348         if (!is_bibtex_)
349                 return docstring();
350         return operator[]("crossref");
351 }
352
353
354 namespace {
355
356 docstring parseOptions(docstring const & format, string & optkey,
357                     docstring & ifpart, docstring & elsepart);
358
359 // Calls parseOptions to deal with an embedded option, such as:
360 //   {%number%[[, no.~%number%]]}
361 // which must appear at the start of format. ifelsepart gets the
362 // whole of the option, and we return what's left after the option.
363 // we return format if there is an error.
364 docstring parseEmbeddedOption(docstring const & format, docstring & ifelsepart)
365 {
366         LASSERT(format[0] == '{' && format[1] == '%', return format);
367         string optkey;
368         docstring ifpart;
369         docstring elsepart;
370         docstring const rest = parseOptions(format, optkey, ifpart, elsepart);
371         if (format == rest) { // parse error
372                 LYXERR0("ERROR! Couldn't parse `" << format <<"'.");
373                 return format;
374         }
375         LASSERT(rest.size() <= format.size(),
376                 { ifelsepart = docstring(); return format; });
377         ifelsepart = format.substr(0, format.size() - rest.size());
378         return rest;
379 }
380
381
382 // Gets a "clause" from a format string, where the clause is
383 // delimited by '[[' and ']]'. Returns what is left after the
384 // clause is removed, and returns format if there is an error.
385 docstring getClause(docstring const & format, docstring & clause)
386 {
387         docstring fmt = format;
388         // remove '[['
389         fmt = fmt.substr(2);
390         // we'll remove characters from the front of fmt as we
391         // deal with them
392         while (!fmt.empty()) {
393                 if (fmt[0] == ']' && fmt.size() > 1 && fmt[1] == ']') {
394                         // that's the end
395                         fmt = fmt.substr(2);
396                         break;
397                 }
398                 // check for an embedded option
399                 if (fmt[0] == '{' && fmt.size() > 1 && fmt[1] == '%') {
400                         docstring part;
401                         docstring const rest = parseEmbeddedOption(fmt, part);
402                         if (fmt == rest) {
403                                 LYXERR0("ERROR! Couldn't parse embedded option in `" << format <<"'.");
404                                 return format;
405                         }
406                         clause += part;
407                         fmt = rest;
408                 } else { // it's just a normal character
409                                 clause += fmt[0];
410                                 fmt = fmt.substr(1);
411                 }
412         }
413         return fmt;
414 }
415
416
417 // parse an options string, which must appear at the start of the
418 // format parameter. puts the parsed bits in optkey, ifpart, and
419 // elsepart and returns what's left after the option is removed.
420 // if there's an error, it returns format itself.
421 docstring parseOptions(docstring const & format, string & optkey,
422                     docstring & ifpart, docstring & elsepart)
423 {
424         LASSERT(format[0] == '{' && format[1] == '%', return format);
425         // strip '{%'
426         docstring fmt = format.substr(2);
427         size_t pos = fmt.find('%'); // end of key
428         if (pos == string::npos) {
429                 LYXERR0("Error parsing  `" << format <<"'. Can't find end of key.");
430                 return format;
431         }
432         optkey = to_utf8(fmt.substr(0, pos));
433         fmt = fmt.substr(pos + 1);
434         // [[format]] should be next
435         if (fmt[0] != '[' || fmt[1] != '[') {
436                 LYXERR0("Error parsing  `" << format <<"'. Can't find '[[' after key.");
437                 return format;
438         }
439
440         docstring curfmt = fmt;
441         fmt = getClause(curfmt, ifpart);
442         if (fmt == curfmt) {
443                 LYXERR0("Error parsing  `" << format <<"'. Couldn't get if clause.");
444                 return format;
445         }
446
447         if (fmt[0] == '}') // we're done, no else clause
448                 return fmt.substr(1);
449
450         // else part should follow
451         if (fmt[0] != '[' || fmt[1] != '[') {
452                 LYXERR0("Error parsing  `" << format <<"'. Can't find else clause.");
453                 return format;
454         }
455
456         curfmt = fmt;
457         fmt = getClause(curfmt, elsepart);
458         // we should be done
459         if (fmt == curfmt || fmt[0] != '}') {
460                 LYXERR0("Error parsing  `" << format <<"'. Can't find end of option.");
461                 return format;
462         }
463         return fmt.substr(1);
464 }
465
466
467 } // anon namespace
468
469
470 docstring BibTeXInfo::expandFormat(docstring const & format,
471                 BibTeXInfo const * const xref, int & counter, Buffer const & buf,
472                 docstring before, docstring after, docstring dialog, bool next) const
473 {
474         // incorrect use of macros could put us in an infinite loop
475         static int const max_passes = 5000;
476         // the use of overly large keys can lead to performance problems, due
477         // to eventual attempts to convert LaTeX macros to unicode. See bug
478         // #8944. This is perhaps not the best solution, but it will have to
479         // do for now.
480         static size_t const max_keysize = 128;
481         odocstringstream ret; // return value
482         string key;
483         bool scanning_key = false;
484         bool scanning_rich = false;
485
486         CiteEngineType const engine_type = buf.params().citeEngineType();
487         docstring fmt = format;
488         // we'll remove characters from the front of fmt as we
489         // deal with them
490         while (!fmt.empty()) {
491                 if (counter++ > max_passes) {
492                         LYXERR0("Recursion limit reached while parsing `"
493                                 << format << "'.");
494                         return _("ERROR!");
495                 }
496
497                 char_type thischar = fmt[0];
498                 if (thischar == '%') {
499                         // beginning or end of key
500                         if (scanning_key) {
501                                 // end of key
502                                 scanning_key = false;
503                                 // so we replace the key with its value, which may be empty
504                                 if (key[0] == '!') {
505                                         // macro
506                                         string const val =
507                                                 buf.params().documentClass().getCiteMacro(engine_type, key);
508                                         fmt = from_utf8(val) + fmt.substr(1);
509                                         continue;
510                                 } else if (key[0] == '_') {
511                                         // a translatable bit
512                                         string const val =
513                                                 buf.params().documentClass().getCiteMacro(engine_type, key);
514                                         docstring const trans =
515                                                 translateIfPossible(from_utf8(val), buf.params().language->code());
516                                         ret << trans;
517                                 } else {
518                                         docstring const val =
519                                                 getValueForKey(key, buf, before, after, dialog, xref, max_keysize);
520                                         if (!scanning_rich)
521                                                 ret << from_ascii("{!<span class=\"bib-" + key + "\">!}");
522                                         ret << val;
523                                         if (!scanning_rich)
524                                                 ret << from_ascii("{!</span>!}");
525                                 }
526                         } else {
527                                 // beginning of key
528                                 key.clear();
529                                 scanning_key = true;
530                         }
531                 }
532                 else if (thischar == '{') {
533                         // beginning of option?
534                         if (scanning_key) {
535                                 LYXERR0("ERROR: Found `{' when scanning key in `" << format << "'.");
536                                 return _("ERROR!");
537                         }
538                         if (fmt.size() > 1) {
539                                 if (fmt[1] == '%') {
540                                         // it is the beginning of an optional format
541                                         string optkey;
542                                         docstring ifpart;
543                                         docstring elsepart;
544                                         docstring const newfmt =
545                                                 parseOptions(fmt, optkey, ifpart, elsepart);
546                                         if (newfmt == fmt) // parse error
547                                                 return _("ERROR!");
548                                         fmt = newfmt;
549                                         docstring const val =
550                                                 getValueForKey(optkey, buf, before, after, dialog, xref);
551                                         if (optkey == "next" && next)
552                                                 ret << ifpart; // without expansion
553                                         else if (!val.empty())
554                                                 ret << expandFormat(ifpart, xref, counter, buf,
555                                                         before, after, dialog, next);
556                                         else if (!elsepart.empty())
557                                                 ret << expandFormat(elsepart, xref, counter, buf,
558                                                         before, after, dialog, next);
559                                         // fmt will have been shortened for us already
560                                         continue;
561                                 }
562                                 if (fmt[1] == '!') {
563                                         // beginning of rich text
564                                         scanning_rich = true;
565                                         fmt = fmt.substr(2);
566                                         ret << from_ascii("{!");
567                                         continue;
568                                 }
569                         }
570                         // we are here if '{' was not followed by % or !.
571                         // So it's just a character.
572                         ret << thischar;
573                 }
574                 else if (scanning_rich && thischar == '!'
575                          && fmt.size() > 1 && fmt[1] == '}') {
576                         // end of rich text
577                         scanning_rich = false;
578                         fmt = fmt.substr(2);
579                         ret << from_ascii("!}");
580                         continue;
581                 }
582                 else if (scanning_key)
583                         key += char(thischar);
584                 else {
585                         try {
586                                 ret.put(thischar);
587                         } catch (EncodingException & /* e */) {
588                                 LYXERR0("Uncodable character '" << docstring(1, thischar) << " in citation label!");
589                         }
590                 }
591                 fmt = fmt.substr(1);
592         } // for loop
593         if (scanning_key) {
594                 LYXERR0("Never found end of key in `" << format << "'!");
595                 return _("ERROR!");
596         }
597         if (scanning_rich) {
598                 LYXERR0("Never found end of rich text in `" << format << "'!");
599                 return _("ERROR!");
600         }
601         return ret.str();
602 }
603
604
605 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref,
606         Buffer const & buf, bool richtext) const
607 {
608         if (!richtext && !info_.empty())
609                 return info_;
610         if (richtext && !info_richtext_.empty())
611                 return info_richtext_;
612
613         if (!is_bibtex_) {
614                 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
615                 info_ = it->second;
616                 return info_;
617         }
618
619         CiteEngineType const engine_type = buf.params().citeEngineType();
620         DocumentClass const & dc = buf.params().documentClass();
621         docstring const & format =
622                 from_utf8(dc.getCiteFormat(engine_type, to_utf8(entry_type_)));
623         int counter = 0;
624         info_ = expandFormat(format, xref, counter, buf,
625                 docstring(), docstring(), docstring(), false);
626
627         if (info_.empty()) {
628                 // this probably shouldn't happen
629                 return info_;
630         }
631
632         if (richtext) {
633                 info_richtext_ = convertLaTeXCommands(processRichtext(info_, true));
634                 return info_richtext_;
635         }
636
637         info_ = convertLaTeXCommands(processRichtext(info_, false));
638         return info_;
639 }
640
641
642 docstring const BibTeXInfo::getLabel(BibTeXInfo const * const xref,
643         Buffer const & buf, docstring const & format, bool richtext,
644         docstring before, docstring after, docstring dialog, bool next) const
645 {
646         docstring loclabel;
647
648         int counter = 0;
649         loclabel = expandFormat(format, xref, counter, buf,
650                 before, after, dialog, next);
651
652         if (!loclabel.empty() && !next) {
653                 loclabel = processRichtext(loclabel, richtext);
654                 loclabel = convertLaTeXCommands(loclabel);
655         }
656
657         return loclabel;
658 }
659
660
661 docstring const & BibTeXInfo::operator[](docstring const & field) const
662 {
663         BibTeXInfo::const_iterator it = find(field);
664         if (it != end())
665                 return it->second;
666         static docstring const empty_value = docstring();
667         return empty_value;
668 }
669
670
671 docstring const & BibTeXInfo::operator[](string const & field) const
672 {
673         return operator[](from_ascii(field));
674 }
675
676
677 docstring BibTeXInfo::getValueForKey(string const & oldkey, Buffer const & buf,
678         docstring const & before, docstring const & after, docstring const & dialog,
679         BibTeXInfo const * const xref, size_t maxsize) const
680 {
681         // anything less is pointless
682         LASSERT(maxsize >= 16, maxsize = 16);
683         string key = oldkey;
684         bool cleanit = false;
685         if (prefixIs(oldkey, "clean:")) {
686                 key = oldkey.substr(6);
687                 cleanit = true;
688         }
689
690         docstring ret = operator[](key);
691         if (ret.empty() && xref)
692                 ret = (*xref)[key];
693         if (ret.empty()) {
694                 // some special keys
695                 // FIXME: dialog, textbefore and textafter have nothing to do with this
696                 if (key == "dialog")
697                         ret = dialog;
698                 else if (key == "entrytype")
699                         ret = entry_type_;
700                 else if (key == "key")
701                         ret = bib_key_;
702                 else if (key == "label")
703                         ret = label_;
704                 else if (key == "modifier" && modifier_ != 0)
705                         ret = modifier_;
706                 else if (key == "numericallabel")
707                         ret = cite_number_;
708                 else if (key == "abbrvauthor")
709                         // Special key to provide abbreviated author names.
710                         ret = getAbbreviatedAuthor(buf, false);
711                 else if (key == "shortauthor")
712                         // When shortauthor is not defined, jurabib automatically
713                         // provides jurabib-style abbreviated author names. We do
714                         // this as well.
715                         ret = getAbbreviatedAuthor(buf, true);
716                 else if (key == "shorttitle") {
717                         // When shorttitle is not defined, jurabib uses for `article'
718                         // and `periodical' entries the form `journal volume [year]'
719                         // and for other types of entries it uses the `title' field.
720                         if (entry_type_ == "article" || entry_type_ == "periodical")
721                                 ret = operator[]("journal") + " " + operator[]("volume")
722                                         + " [" + operator[]("year") + "]";
723                         else
724                                 ret = operator[]("title");
725                 } else if (key == "bibentry") {
726                         // Special key to provide the full bibliography entry: see getInfo()
727                         CiteEngineType const engine_type = buf.params().citeEngineType();
728                         DocumentClass const & dc = buf.params().documentClass();
729                         docstring const & format =
730                                 from_utf8(dc.getCiteFormat(engine_type, to_utf8(entry_type_)));
731                         int counter = 0;
732                         ret = expandFormat(format, xref, counter, buf,
733                                 docstring(), docstring(), docstring(), false);
734                 } else if (key == "textbefore")
735                         ret = before;
736                 else if (key == "textafter")
737                         ret = after;
738                 else if (key == "year")
739                         ret = getYear();
740         }
741
742         if (cleanit)
743                 ret = html::cleanAttr(ret);
744
745         // make sure it is not too big
746         if (ret.size() > maxsize)
747                 ret = ret.substr(0, maxsize - 3) + from_ascii("...");
748         return ret;
749 }
750
751
752 //////////////////////////////////////////////////////////////////////
753 //
754 // BiblioInfo
755 //
756 //////////////////////////////////////////////////////////////////////
757
758 namespace {
759
760 // A functor for use with sort, leading to case insensitive sorting
761 class compareNoCase: public binary_function<docstring, docstring, bool>
762 {
763 public:
764         bool operator()(docstring const & s1, docstring const & s2) const {
765                 return compare_no_case(s1, s2) < 0;
766         }
767 };
768
769 } // namespace anon
770
771
772 vector<docstring> const BiblioInfo::getKeys() const
773 {
774         vector<docstring> bibkeys;
775         BiblioInfo::const_iterator it  = begin();
776         for (; it != end(); ++it)
777                 bibkeys.push_back(it->first);
778         sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
779         return bibkeys;
780 }
781
782
783 vector<docstring> const BiblioInfo::getFields() const
784 {
785         vector<docstring> bibfields;
786         set<docstring>::const_iterator it = field_names_.begin();
787         set<docstring>::const_iterator end = field_names_.end();
788         for (; it != end; ++it)
789                 bibfields.push_back(*it);
790         sort(bibfields.begin(), bibfields.end());
791         return bibfields;
792 }
793
794
795 vector<docstring> const BiblioInfo::getEntries() const
796 {
797         vector<docstring> bibentries;
798         set<docstring>::const_iterator it = entry_types_.begin();
799         set<docstring>::const_iterator end = entry_types_.end();
800         for (; it != end; ++it)
801                 bibentries.push_back(*it);
802         sort(bibentries.begin(), bibentries.end());
803         return bibentries;
804 }
805
806
807 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key, Buffer const & buf) const
808 {
809         BiblioInfo::const_iterator it = find(key);
810         if (it == end())
811                 return docstring();
812         BibTeXInfo const & data = it->second;
813         return data.getAbbreviatedAuthor(buf, false);
814 }
815
816
817 docstring const BiblioInfo::getCiteNumber(docstring const & key) const
818 {
819         BiblioInfo::const_iterator it = find(key);
820         if (it == end())
821                 return docstring();
822         BibTeXInfo const & data = it->second;
823         return data.citeNumber();
824 }
825
826
827 docstring const BiblioInfo::getYear(docstring const & key, bool use_modifier) const
828 {
829         BiblioInfo::const_iterator it = find(key);
830         if (it == end())
831                 return docstring();
832         BibTeXInfo const & data = it->second;
833         docstring year = data.getYear();
834         if (year.empty()) {
835                 // let's try the crossref
836                 docstring const xref = data.getXRef();
837                 if (xref.empty())
838                         // no luck
839                         return docstring();
840                 BiblioInfo::const_iterator const xrefit = find(xref);
841                 if (xrefit == end())
842                         // no luck again
843                         return docstring();
844                 BibTeXInfo const & xref_data = xrefit->second;
845                 year = xref_data.getYear();
846         }
847         if (use_modifier && data.modifier() != 0)
848                 year += data.modifier();
849         return year;
850 }
851
852
853 docstring const BiblioInfo::getYear(docstring const & key, Buffer const & buf, bool use_modifier) const
854 {
855         docstring const year = getYear(key, use_modifier);
856         if (year.empty())
857                 return buf.B_("No year");
858         return year;
859 }
860
861
862 docstring const BiblioInfo::getInfo(docstring const & key,
863         Buffer const & buf, bool richtext) const
864 {
865         BiblioInfo::const_iterator it = find(key);
866         if (it == end())
867                 return docstring(_("Bibliography entry not found!"));
868         BibTeXInfo const & data = it->second;
869         BibTeXInfo const * xrefptr = 0;
870         docstring const xref = data.getXRef();
871         if (!xref.empty()) {
872                 BiblioInfo::const_iterator const xrefit = find(xref);
873                 if (xrefit != end())
874                         xrefptr = &(xrefit->second);
875         }
876         return data.getInfo(xrefptr, buf, richtext);
877 }
878
879
880 docstring const BiblioInfo::getLabel(vector<docstring> const & keys,
881         Buffer const & buf, string const & style, bool richtext,
882         docstring const & before, docstring const & after, docstring const & dialog) const
883 {
884         CiteEngineType const engine_type = buf.params().citeEngineType();
885         DocumentClass const & dc = buf.params().documentClass();
886         docstring const & format = from_utf8(dc.getCiteFormat(engine_type, style, "cite"));
887         docstring ret = format;
888         vector<docstring>::const_iterator key = keys.begin();
889         vector<docstring>::const_iterator ken = keys.end();
890         for (; key != ken; ++key) {
891                 BiblioInfo::const_iterator it = find(*key);
892                 BibTeXInfo empty_data;
893                 empty_data.key(*key);
894                 BibTeXInfo & data = empty_data;
895                 BibTeXInfo const * xrefptr = 0;
896                 if (it != end()) {
897                         data = it->second;
898                         docstring const xref = data.getXRef();
899                         if (!xref.empty()) {
900                                 BiblioInfo::const_iterator const xrefit = find(xref);
901                                 if (xrefit != end())
902                                         xrefptr = &(xrefit->second);
903                         }
904                 }
905                 ret = data.getLabel(xrefptr, buf, ret, richtext,
906                         before, after, dialog, key+1 != ken);
907         }
908         return ret;
909 }
910
911
912 bool BiblioInfo::isBibtex(docstring const & key) const
913 {
914         BiblioInfo::const_iterator it = find(key);
915         if (it == end())
916                 return false;
917         return it->second.isBibTeX();
918 }
919
920
921 vector<docstring> const BiblioInfo::getCiteStrings(
922         vector<docstring> const & keys, vector<CitationStyle> const & styles,
923         Buffer const & buf, bool richtext, docstring const & before,
924         docstring const & after, docstring const & dialog) const
925 {
926         if (empty())
927                 return vector<docstring>();
928
929         string style;
930         vector<docstring> vec(styles.size());
931         for (size_t i = 0; i != vec.size(); ++i) {
932                 style = styles[i].cmd;
933                 vec[i] = getLabel(keys, buf, style, richtext, before, after, dialog);
934         }
935
936         return vec;
937 }
938
939
940 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
941 {
942         bimap_.insert(info.begin(), info.end());
943         field_names_.insert(info.field_names_.begin(), info.field_names_.end());
944         entry_types_.insert(info.entry_types_.begin(), info.entry_types_.end());
945 }
946
947
948 namespace {
949
950 // used in xhtml to sort a list of BibTeXInfo objects
951 bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
952 {
953         docstring const lauth = lhs->getAbbreviatedAuthor();
954         docstring const rauth = rhs->getAbbreviatedAuthor();
955         docstring const lyear = lhs->getYear();
956         docstring const ryear = rhs->getYear();
957         docstring const ltitl = lhs->operator[]("title");
958         docstring const rtitl = rhs->operator[]("title");
959         return  (lauth < rauth)
960                 || (lauth == rauth && lyear < ryear)
961                 || (lauth == rauth && lyear == ryear && ltitl < rtitl);
962 }
963
964 }
965
966
967 void BiblioInfo::collectCitedEntries(Buffer const & buf)
968 {
969         cited_entries_.clear();
970         // We are going to collect all the citation keys used in the document,
971         // getting them from the TOC.
972         // FIXME We may want to collect these differently, in the first case,
973         // so that we might have them in order of appearance.
974         set<docstring> citekeys;
975         Toc const & toc = buf.tocBackend().toc("citation");
976         Toc::const_iterator it = toc.begin();
977         Toc::const_iterator const en = toc.end();
978         for (; it != en; ++it) {
979                 if (it->str().empty())
980                         continue;
981                 vector<docstring> const keys = getVectorFromString(it->str());
982                 citekeys.insert(keys.begin(), keys.end());
983         }
984         if (citekeys.empty())
985                 return;
986
987         // We have a set of the keys used in this document.
988         // We will now convert it to a list of the BibTeXInfo objects used in
989         // this document...
990         vector<BibTeXInfo const *> bi;
991         set<docstring>::const_iterator cit = citekeys.begin();
992         set<docstring>::const_iterator const cen = citekeys.end();
993         for (; cit != cen; ++cit) {
994                 BiblioInfo::const_iterator const bt = find(*cit);
995                 if (bt == end() || !bt->second.isBibTeX())
996                         continue;
997                 bi.push_back(&(bt->second));
998         }
999         // ...and sort it.
1000         sort(bi.begin(), bi.end(), lSorter);
1001
1002         // Now we can write the sorted keys
1003         vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
1004         vector<BibTeXInfo const *>::const_iterator ben = bi.end();
1005         for (; bit != ben; ++bit)
1006                 cited_entries_.push_back((*bit)->key());
1007 }
1008
1009
1010 void BiblioInfo::makeCitationLabels(Buffer const & buf)
1011 {
1012         collectCitedEntries(buf);
1013         CiteEngineType const engine_type = buf.params().citeEngineType();
1014         bool const numbers = (engine_type & ENGINE_TYPE_NUMERICAL);
1015
1016         int keynumber = 0;
1017         char modifier = 0;
1018         // used to remember the last one we saw
1019         // we'll be comparing entries to see if we need to add
1020         // modifiers, like "1984a"
1021         map<docstring, BibTeXInfo>::iterator last;
1022
1023         vector<docstring>::const_iterator it = cited_entries_.begin();
1024         vector<docstring>::const_iterator const en = cited_entries_.end();
1025         for (; it != en; ++it) {
1026                 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
1027                 // this shouldn't happen, but...
1028                 if (biit == bimap_.end())
1029                         // ...fail gracefully, anyway.
1030                         continue;
1031                 BibTeXInfo & entry = biit->second;
1032                 if (numbers) {
1033                         docstring const num = convert<docstring>(++keynumber);
1034                         entry.setCiteNumber(num);
1035                 } else {
1036                         if (it != cited_entries_.begin()
1037                             && entry.getAbbreviatedAuthor() == last->second.getAbbreviatedAuthor()
1038                             // we access the year via getYear() so as to get it from the xref,
1039                             // if we need to do so
1040                             && getYear(entry.key()) == getYear(last->second.key())) {
1041                                 if (modifier == 0) {
1042                                         // so the last one should have been 'a'
1043                                         last->second.setModifier('a');
1044                                         modifier = 'b';
1045                                 } else if (modifier == 'z')
1046                                         modifier = 'A';
1047                                 else
1048                                         modifier++;
1049                         } else {
1050                                 modifier = 0;
1051                         }
1052                         entry.setModifier(modifier);
1053                         // remember the last one
1054                         last = biit;
1055                 }
1056         }
1057         // Set the labels
1058         it = cited_entries_.begin();
1059         for (; it != en; ++it) {
1060                 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
1061                 // this shouldn't happen, but...
1062                 if (biit == bimap_.end())
1063                         // ...fail gracefully, anyway.
1064                         continue;
1065                 BibTeXInfo & entry = biit->second;
1066                 if (numbers) {
1067                         entry.label(entry.citeNumber());
1068                 } else {
1069                         docstring const auth = entry.getAbbreviatedAuthor(buf, false);
1070                         // we do it this way so as to access the xref, if necessary
1071                         // note that this also gives us the modifier
1072                         docstring const year = getYear(*it, buf, true);
1073                         if (!auth.empty() && !year.empty())
1074                                 entry.label(auth + ' ' + year);
1075                         else
1076                                 entry.label(entry.key());
1077                 }
1078         }
1079 }
1080
1081
1082 //////////////////////////////////////////////////////////////////////
1083 //
1084 // CitationStyle
1085 //
1086 //////////////////////////////////////////////////////////////////////
1087
1088
1089 CitationStyle citationStyleFromString(string const & command)
1090 {
1091         CitationStyle cs;
1092         if (command.empty())
1093                 return cs;
1094
1095         string cmd = command;
1096         if (cmd[0] == 'C') {
1097                 cs.forceUpperCase = true;
1098                 cmd[0] = 'c';
1099         }
1100
1101         size_t const n = cmd.size() - 1;
1102         if (cmd[n] == '*') {
1103                 cs.fullAuthorList = true;
1104                 cmd = cmd.substr(0, n);
1105         }
1106
1107         cs.cmd = cmd;
1108         return cs;
1109 }
1110
1111
1112 string citationStyleToString(const CitationStyle & cs)
1113 {
1114         string cmd = cs.cmd;
1115         if (cs.forceUpperCase)
1116                 cmd[0] = 'C';
1117         if (cs.fullAuthorList)
1118                 cmd += '*';
1119         return cmd;
1120 }
1121
1122 } // namespace lyx