]> git.lyx.org Git - lyx.git/blob - src/BiblioInfo.cpp
Routines for calculating numerical labels for BibTeX citations.
[lyx.git] / src / BiblioInfo.cpp
1 /**
2  * \file BiblioInfo.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  * \author Herbert Voß
8  * \author Richard Heck
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "BiblioInfo.h"
16 #include "Buffer.h"
17 #include "BufferParams.h"
18 #include "buffer_funcs.h"
19 #include "Encoding.h"
20 #include "InsetIterator.h"
21 #include "Paragraph.h"
22 #include "TocBackend.h"
23
24 #include "insets/Inset.h"
25 #include "insets/InsetBibitem.h"
26 #include "insets/InsetBibtex.h"
27 #include "insets/InsetInclude.h"
28
29 #include "support/convert.h"
30 #include "support/docstream.h"
31 #include "support/gettext.h"
32 #include "support/lassert.h"
33 #include "support/lstrings.h"
34 #include "support/textutils.h"
35
36 #include "boost/regex.hpp"
37
38 #include <set>
39
40 using namespace std;
41 using namespace lyx::support;
42
43
44 namespace lyx {
45
46 namespace {
47
48 // gets the "family name" from an author-type string
49 docstring familyName(docstring const & name)
50 {
51         if (name.empty())
52                 return docstring();
53
54         // first we look for a comma, and take the last name to be everything
55         // preceding the right-most one, so that we also get the "jr" part.
56         docstring::size_type idx = name.rfind(',');
57         if (idx != docstring::npos)
58                 return ltrim(name.substr(0, idx));
59
60         // OK, so now we want to look for the last name. We're going to
61         // include the "von" part. This isn't perfect.
62         // Split on spaces, to get various tokens.
63         vector<docstring> pieces = getVectorFromString(name, from_ascii(" "));
64         // If we only get two, assume the last one is the last name
65         if (pieces.size() <= 2)
66                 return pieces.back();
67
68         // Now we look for the first token that begins with a lower case letter.
69         vector<docstring>::const_iterator it = pieces.begin();
70         vector<docstring>::const_iterator en = pieces.end();
71         for (; it != en; ++it) {
72                 if ((*it).size() == 0)
73                         continue;
74                 char_type const c = (*it)[0];
75                 if (isLower(c))
76                         break;
77         }
78
79         if (it == en) // we never found a "von"
80                 return pieces.back();
81
82         // reconstruct what we need to return
83         docstring retval;
84         bool first = true;
85         for (; it != en; ++it) {
86                 if (!first)
87                         retval += " ";
88                 else 
89                         first = false;
90                 retval += *it;
91         }
92         return retval;
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.size()) {
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                 static boost::regex const reg("^\\\\\\W\\w");
176                 if (boost::regex_search(to_utf8(val), reg)) {
177                         val.insert(3, from_ascii("}"));
178                         val.insert(2, from_ascii("{"));
179                 }
180                 docstring rem;
181                 docstring const cnvtd = Encodings::fromLaTeXCommand(val, rem,
182                                                         Encodings::TEXT_CMD);
183                 if (!cnvtd.empty()) {
184                         // it did, so we'll take that bit and proceed with what's left
185                         ret += cnvtd;
186                         val = rem;
187                         continue;
188                 }
189                 // it's a command of some sort
190                 scanning_cmd = true;
191                 escaped = true;
192                 val = val.substr(1);
193         }
194         return ret;
195 }
196
197 } // anon namespace
198
199
200 //////////////////////////////////////////////////////////////////////
201 //
202 // BibTeXInfo
203 //
204 //////////////////////////////////////////////////////////////////////
205
206 BibTeXInfo::BibTeXInfo(docstring const & key, docstring const & type)
207         : is_bibtex_(true), bib_key_(key), entry_type_(type), info_()
208 {}
209
210
211 bool BibTeXInfo::hasField(docstring const & field) const
212 {
213         return count(field) == 1;
214 }
215
216
217 docstring const BibTeXInfo::getAbbreviatedAuthor() const
218 {
219         if (!is_bibtex_) {
220                 docstring const opt = label();
221                 if (opt.empty())
222                         return docstring();
223
224                 docstring authors;
225                 split(opt, authors, '(');
226                 return authors;
227         }
228
229         docstring author = convertLaTeXCommands(operator[]("author"));
230         if (author.empty()) {
231                 author = convertLaTeXCommands(operator[]("editor"));
232                 if (author.empty())
233                         return bib_key_;
234         }
235
236         // OK, we've got some names. Let's format them.
237         // Try to split the author list on " and "
238         vector<docstring> const authors =
239                 getVectorFromString(author, from_ascii(" and "));
240
241         if (authors.size() == 2)
242                 return bformat(_("%1$s and %2$s"),
243                         familyName(authors[0]), familyName(authors[1]));
244
245         if (authors.size() > 2)
246                 return bformat(_("%1$s et al."), familyName(authors[0]));
247
248         return familyName(authors[0]);
249 }
250
251
252 docstring const BibTeXInfo::getYear() const
253 {
254         if (is_bibtex_) 
255                 return operator[]("year");
256
257         docstring const opt = label();
258         if (opt.empty())
259                 return docstring();
260
261         docstring authors;
262         docstring const tmp = split(opt, authors, '(');
263         docstring year;
264         split(tmp, year, ')');
265         return year;
266 }
267
268
269 docstring const BibTeXInfo::getXRef() const
270 {
271         if (!is_bibtex_)
272                 return docstring();
273         return operator[]("crossref");
274 }
275
276
277 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref) const
278 {
279         if (!info_.empty())
280                 return info_;
281
282         if (!is_bibtex_) {
283                 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
284                 info_ = it->second;
285                 return info_;
286         }
287  
288         // FIXME
289         // This could be made a lot better using the entry_type_
290         // field to customize the output based upon entry type.
291         
292         // Search for all possible "required" fields
293         docstring author = getValueForKey("author", xref);
294         if (author.empty())
295                 author = getValueForKey("editor", xref);
296  
297         docstring year   = getValueForKey("year", xref);
298         docstring title  = getValueForKey("title", xref);
299         docstring docLoc = getValueForKey("pages", xref);
300         if (docLoc.empty()) {
301                 docLoc = getValueForKey("chapter", xref);
302                 if (!docLoc.empty())
303                         docLoc = _("Ch. ") + docLoc;
304         }       else {
305                 docLoc = _("pp. ") + docLoc;
306         }
307
308         docstring media = getValueForKey("journal", xref);
309         if (media.empty()) {
310                 media = getValueForKey("publisher", xref);
311                 if (media.empty()) {
312                         media = getValueForKey("school", xref);
313                         if (media.empty())
314                                 media = getValueForKey("institution");
315                 }
316         }
317         docstring volume = getValueForKey("volume", xref);
318
319         odocstringstream result;
320         if (!author.empty())
321                 result << author << ", ";
322         if (!title.empty())
323                 result << title;
324         if (!media.empty())
325                 result << ", " << media;
326         if (!year.empty())
327                 result << " (" << year << ")";
328         if (!docLoc.empty())
329                 result << ", " << docLoc;
330
331         docstring const result_str = rtrim(result.str());
332         if (!result_str.empty()) {
333                 info_ = convertLaTeXCommands(result_str);
334                 return info_;
335         }
336
337         // This should never happen (or at least be very unusual!)
338         static docstring e = docstring();
339         return e;
340 }
341
342
343 docstring const & BibTeXInfo::operator[](docstring const & field) const
344 {
345         BibTeXInfo::const_iterator it = find(field);
346         if (it != end())
347                 return it->second;
348         static docstring const empty_value = docstring();
349         return empty_value;
350 }
351         
352         
353 docstring const & BibTeXInfo::operator[](string const & field) const
354 {
355         return operator[](from_ascii(field));
356 }
357
358
359 docstring BibTeXInfo::getValueForKey(string const & key, 
360                 BibTeXInfo const * const xref) const
361 {
362         docstring const ret = operator[](key);
363         if (!ret.empty() || !xref)
364                 return ret;
365         return (*xref)[key];
366 }
367
368
369 //////////////////////////////////////////////////////////////////////
370 //
371 // BiblioInfo
372 //
373 //////////////////////////////////////////////////////////////////////
374
375 namespace {
376 // A functor for use with sort, leading to case insensitive sorting
377         class compareNoCase: public binary_function<docstring, docstring, bool>
378         {
379                 public:
380                         bool operator()(docstring const & s1, docstring const & s2) const {
381                                 return compare_no_case(s1, s2) < 0;
382                         }
383         };
384 } // namespace anon
385
386
387 vector<docstring> const BiblioInfo::getKeys() const
388 {
389         vector<docstring> bibkeys;
390         BiblioInfo::const_iterator it  = begin();
391         for (; it != end(); ++it)
392                 bibkeys.push_back(it->first);
393         sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
394         return bibkeys;
395 }
396
397
398 vector<docstring> const BiblioInfo::getFields() const
399 {
400         vector<docstring> bibfields;
401         set<docstring>::const_iterator it = field_names_.begin();
402         set<docstring>::const_iterator end = field_names_.end();
403         for (; it != end; ++it)
404                 bibfields.push_back(*it);
405         sort(bibfields.begin(), bibfields.end());
406         return bibfields;
407 }
408
409
410 vector<docstring> const BiblioInfo::getEntries() const
411 {
412         vector<docstring> bibentries;
413         set<docstring>::const_iterator it = entry_types_.begin();
414         set<docstring>::const_iterator end = entry_types_.end();
415         for (; it != end; ++it)
416                 bibentries.push_back(*it);
417         sort(bibentries.begin(), bibentries.end());
418         return bibentries;
419 }
420
421
422 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
423 {
424         BiblioInfo::const_iterator it = find(key);
425         if (it == end())
426                 return docstring();
427         BibTeXInfo const & data = it->second;
428         return data.getAbbreviatedAuthor();
429 }
430
431
432 docstring const BiblioInfo::getYear(docstring const & key) const
433 {
434         BiblioInfo::const_iterator it = find(key);
435         if (it == end())
436                 return docstring();
437         BibTeXInfo const & data = it->second;
438         docstring year = data.getYear();
439         if (!year.empty())
440                 return year;
441         // let's try the crossref
442         docstring const xref = data.getXRef();
443         if (xref.empty())
444                 return _("No year"); // no luck
445         BiblioInfo::const_iterator const xrefit = find(xref);
446         if (xrefit == end())
447                 return _("No year"); // no luck again
448         BibTeXInfo const & xref_data = xrefit->second;
449         return xref_data.getYear();
450         return data.getYear();
451 }
452
453
454 docstring const BiblioInfo::getInfo(docstring const & key) const
455 {
456         BiblioInfo::const_iterator it = find(key);
457         if (it == end())
458                 return docstring();
459         BibTeXInfo const & data = it->second;
460         BibTeXInfo const * xrefptr = 0;
461         docstring const xref = data.getXRef();
462         if (!xref.empty()) {
463                 BiblioInfo::const_iterator const xrefit = find(xref);
464                 if (xrefit != end())
465                         xrefptr = &(xrefit->second);
466         }
467         return data.getInfo(xrefptr);
468 }
469
470
471 vector<docstring> const BiblioInfo::getCiteStrings(
472         docstring const & key, Buffer const & buf) const
473 {
474         CiteEngine const engine = buf.params().citeEngine();
475         if (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL)
476                 return getNumericalStrings(key, buf);
477         else
478                 return getAuthorYearStrings(key, buf);
479 }
480
481
482 vector<docstring> const BiblioInfo::getNumericalStrings(
483         docstring const & key, Buffer const & buf) const
484 {
485         if (empty())
486                 return vector<docstring>();
487
488         docstring const author = getAbbreviatedAuthor(key);
489         docstring const year   = getYear(key);
490         if (author.empty() || year.empty())
491                 return vector<docstring>();
492
493         vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
494         
495         vector<docstring> vec(styles.size());
496         for (size_t i = 0; i != vec.size(); ++i) {
497                 docstring str;
498
499                 switch (styles[i]) {
500                         case CITE:
501                         case CITEP:
502                                 str = from_ascii("[#ID]");
503                                 break;
504
505                         case NOCITE:
506                                 str = _("Add to bibliography only.");
507                                 break;
508
509                         case CITET:
510                                 str = author + " [#ID]";
511                                 break;
512
513                         case CITEALT:
514                                 str = author + " #ID";
515                                 break;
516
517                         case CITEALP:
518                                 str = from_ascii("#ID");
519                                 break;
520
521                         case CITEAUTHOR:
522                                 str = author;
523                                 break;
524
525                         case CITEYEAR:
526                                 str = year;
527                                 break;
528
529                         case CITEYEARPAR:
530                                 str = '(' + year + ')';
531                                 break;
532                 }
533
534                 vec[i] = str;
535         }
536
537         return vec;
538 }
539
540
541 vector<docstring> const BiblioInfo::getAuthorYearStrings(
542         docstring const & key, Buffer const & buf) const
543 {
544         if (empty())
545                 return vector<docstring>();
546
547         docstring const author = getAbbreviatedAuthor(key);
548         docstring const year   = getYear(key);
549         if (author.empty() || year.empty())
550                 return vector<docstring>();
551
552         vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
553         
554         vector<docstring> vec(styles.size());
555         for (size_t i = 0; i != vec.size(); ++i) {
556                 docstring str;
557
558                 switch (styles[i]) {
559                         case CITE:
560                 // jurabib only: Author/Annotator
561                 // (i.e. the "before" field, 2nd opt arg)
562                                 str = author + "/<" + _("before") + '>';
563                                 break;
564
565                         case NOCITE:
566                                 str = _("Add to bibliography only.");
567                                 break;
568
569                         case CITET:
570                                 str = author + " (" + year + ')';
571                                 break;
572
573                         case CITEP:
574                                 str = '(' + author + ", " + year + ')';
575                                 break;
576
577                         case CITEALT:
578                                 str = author + ' ' + year ;
579                                 break;
580
581                         case CITEALP:
582                                 str = author + ", " + year ;
583                                 break;
584
585                         case CITEAUTHOR:
586                                 str = author;
587                                 break;
588
589                         case CITEYEAR:
590                                 str = year;
591                                 break;
592
593                         case CITEYEARPAR:
594                                 str = '(' + year + ')';
595                                 break;
596                 }
597                 vec[i] = str;
598         }
599         return vec;
600 }
601
602
603 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
604 {
605         bimap_.insert(info.begin(), info.end());
606 }
607
608
609 namespace {
610         // used in xhtml to sort a list of BibTeXInfo objects
611         bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
612         {
613                 return lhs->getAbbreviatedAuthor() < rhs->getAbbreviatedAuthor();
614         }
615 }
616
617
618 void BiblioInfo::collectCitedEntries(Buffer const & buf)
619 {
620         cited_entries_.clear();
621         // We are going to collect all the citation keys used in the document,
622         // getting them from the TOC.
623         // FIXME We may want to collect these differently, in the first case,
624         // so that we might have them in order of appearance.
625         set<docstring> citekeys;
626         Toc const & toc = buf.tocBackend().toc("citation");
627         Toc::const_iterator it = toc.begin();
628         Toc::const_iterator const en = toc.end();
629         for (; it != en; ++it) {
630                 if (it->str().empty())
631                         continue;
632                 vector<docstring> const keys = getVectorFromString(it->str());
633                 citekeys.insert(keys.begin(), keys.end());
634         }
635         if (citekeys.empty())
636                 return;
637         
638         // We have a set of the keys used in this document.
639         // We will now convert it to a list of the BibTeXInfo objects used in 
640         // this document...
641         vector<BibTeXInfo const *> bi;
642         set<docstring>::const_iterator cit = citekeys.begin();
643         set<docstring>::const_iterator const cen = citekeys.end();
644         for (; cit != cen; ++cit) {
645                 BiblioInfo::const_iterator const bt = find(*cit);
646                 if (bt == end() || !bt->second.isBibTeX())
647                         continue;
648                 bi.push_back(&(bt->second));
649         }
650         // ...and sort it.
651         sort(bi.begin(), bi.end(), lSorter);
652         
653         // Now we can write the sorted keys
654         vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
655         vector<BibTeXInfo const *>::const_iterator ben = bi.end();
656         for (; bit != ben; ++bit)
657                 cited_entries_.push_back((*bit)->key());
658 }
659
660
661 void BiblioInfo::makeCitationLabels(Buffer const & buf)
662 {
663         collectCitedEntries(buf);
664         // FIXME It'd be nice to do author-year as well as numerical
665         // and maybe even some other sorts of labels.
666         vector<docstring>::const_iterator it = cited_entries_.begin();
667         vector<docstring>::const_iterator const en = cited_entries_.end();
668         int keynumber = 0;
669         for (; it != en; ++it) {
670                 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
671                 // this shouldn't happen, but...
672                 if (biit == bimap_.end())
673                         continue;
674                 BibTeXInfo & entry = biit->second;
675                 docstring const key = convert<docstring>(++keynumber);
676                 entry.setCiteKey(key);
677         }
678 }
679
680
681 //////////////////////////////////////////////////////////////////////
682 //
683 // CitationStyle
684 //
685 //////////////////////////////////////////////////////////////////////
686
687 namespace {
688
689
690 char const * const citeCommands[] = {
691         "cite", "citet", "citep", "citealt", "citealp",
692         "citeauthor", "citeyear", "citeyearpar", "nocite" };
693
694 unsigned int const nCiteCommands =
695                 sizeof(citeCommands) / sizeof(char *);
696
697 CiteStyle const citeStylesArray[] = {
698         CITE, CITET, CITEP, CITEALT, CITEALP, 
699         CITEAUTHOR, CITEYEAR, CITEYEARPAR, NOCITE };
700
701 unsigned int const nCiteStyles =
702                 sizeof(citeStylesArray) / sizeof(CiteStyle);
703
704 CiteStyle const citeStylesFull[] = {
705         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
706
707 unsigned int const nCiteStylesFull =
708                 sizeof(citeStylesFull) / sizeof(CiteStyle);
709
710 CiteStyle const citeStylesUCase[] = {
711         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
712
713 unsigned int const nCiteStylesUCase =
714         sizeof(citeStylesUCase) / sizeof(CiteStyle);
715
716 } // namespace anon
717
718
719 CitationStyle citationStyleFromString(string const & command)
720 {
721         CitationStyle s;
722         if (command.empty())
723                 return s;
724
725         string cmd = command;
726         if (cmd[0] == 'C') {
727                 s.forceUpperCase = true;
728                 cmd[0] = 'c';
729         }
730
731         size_t const n = cmd.size() - 1;
732         if (cmd != "cite" && cmd[n] == '*') {
733                 s.full = true;
734                 cmd = cmd.substr(0, n);
735         }
736
737         char const * const * const last = citeCommands + nCiteCommands;
738         char const * const * const ptr = find(citeCommands, last, cmd);
739
740         if (ptr != last) {
741                 size_t idx = ptr - citeCommands;
742                 s.style = citeStylesArray[idx];
743         }
744         return s;
745 }
746
747
748 string citationStyleToString(const CitationStyle & s)
749 {
750         string cite = citeCommands[s.style];
751         if (s.full) {
752                 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
753                 if (std::find(citeStylesFull, last, s.style) != last)
754                         cite += '*';
755         }
756
757         if (s.forceUpperCase) {
758                 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
759                 if (std::find(citeStylesUCase, last, s.style) != last)
760                         cite[0] = 'C';
761         }
762
763         return cite;
764 }
765
766 vector<CiteStyle> citeStyles(CiteEngine engine)
767 {
768         unsigned int nStyles = 0;
769         unsigned int start = 0;
770
771         switch (engine) {
772                 case ENGINE_BASIC:
773                         nStyles = 2;
774                         start = 0;
775                         break;
776                 case ENGINE_NATBIB_AUTHORYEAR:
777                 case ENGINE_NATBIB_NUMERICAL:
778                         nStyles = nCiteStyles - 1;
779                         start = 1;
780                         break;
781                 case ENGINE_JURABIB:
782                         nStyles = nCiteStyles;
783                         start = 0;
784                         break;
785         }
786
787         vector<CiteStyle> styles(nStyles);
788         size_t i = 0;
789         int j = start;
790         for (; i != styles.size(); ++i, ++j)
791                 styles[i] = citeStylesArray[j];
792
793         return styles;
794 }
795
796 } // namespace lyx
797