]> git.lyx.org Git - lyx.git/blob - src/BiblioInfo.cpp
* InsetInclude{.cpp, h}:
[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 docstring const BibTeXInfo::getAbbreviatedAuthor() const
212 {
213         if (!is_bibtex_) {
214                 docstring const opt = label();
215                 if (opt.empty())
216                         return docstring();
217
218                 docstring authors;
219                 split(opt, authors, '(');
220                 return authors;
221         }
222
223         docstring author = convertLaTeXCommands(operator[]("author"));
224         if (author.empty()) {
225                 author = convertLaTeXCommands(operator[]("editor"));
226                 if (author.empty())
227                         return bib_key_;
228         }
229
230         // OK, we've got some names. Let's format them.
231         // Try to split the author list on " and "
232         vector<docstring> const authors =
233                 getVectorFromString(author, from_ascii(" and "));
234
235         if (authors.size() == 2)
236                 return bformat(_("%1$s and %2$s"),
237                         familyName(authors[0]), familyName(authors[1]));
238
239         if (authors.size() > 2)
240                 return bformat(_("%1$s et al."), familyName(authors[0]));
241
242         return familyName(authors[0]);
243 }
244
245
246 docstring const BibTeXInfo::getYear() const
247 {
248         if (is_bibtex_) 
249                 return operator[]("year");
250
251         docstring const opt = label();
252         if (opt.empty())
253                 return docstring();
254
255         docstring authors;
256         docstring const tmp = split(opt, authors, '(');
257         docstring year;
258         split(tmp, year, ')');
259         return year;
260 }
261
262
263 docstring const BibTeXInfo::getXRef() const
264 {
265         if (!is_bibtex_)
266                 return docstring();
267         return operator[]("crossref");
268 }
269
270
271 docstring const & BibTeXInfo::getInfo(BibTeXInfo const * const xref) const
272 {
273         if (!info_.empty())
274                 return info_;
275
276         if (!is_bibtex_) {
277                 BibTeXInfo::const_iterator it = find(from_ascii("ref"));
278                 info_ = it->second;
279                 return info_;
280         }
281  
282         // FIXME
283         // This could be made a lot better using the entry_type_
284         // field to customize the output based upon entry type.
285         
286         // Search for all possible "required" fields
287         docstring author = getValueForKey("author", xref);
288         if (author.empty())
289                 author = getValueForKey("editor", xref);
290  
291         docstring year   = getValueForKey("year", xref);
292         docstring title  = getValueForKey("title", xref);
293         docstring docLoc = getValueForKey("pages", xref);
294         if (docLoc.empty()) {
295                 docLoc = getValueForKey("chapter", xref);
296                 if (!docLoc.empty())
297                         docLoc = _("Ch. ") + docLoc;
298         }       else {
299                 docLoc = _("pp. ") + docLoc;
300         }
301
302         docstring media = getValueForKey("journal", xref);
303         if (media.empty()) {
304                 media = getValueForKey("publisher", xref);
305                 if (media.empty()) {
306                         media = getValueForKey("school", xref);
307                         if (media.empty())
308                                 media = getValueForKey("institution");
309                 }
310         }
311         docstring volume = getValueForKey("volume", xref);
312
313         odocstringstream result;
314         if (!author.empty())
315                 result << author << ", ";
316         if (!title.empty())
317                 result << title;
318         if (!media.empty())
319                 result << ", " << media;
320         if (!year.empty())
321                 result << " (" << year << ")";
322         if (!docLoc.empty())
323                 result << ", " << docLoc;
324
325         docstring const result_str = rtrim(result.str());
326         if (!result_str.empty()) {
327                 info_ = convertLaTeXCommands(result_str);
328                 return info_;
329         }
330
331         // This should never happen (or at least be very unusual!)
332         static docstring e = docstring();
333         return e;
334 }
335
336
337 docstring const & BibTeXInfo::operator[](docstring const & field) const
338 {
339         BibTeXInfo::const_iterator it = find(field);
340         if (it != end())
341                 return it->second;
342         static docstring const empty_value = docstring();
343         return empty_value;
344 }
345         
346         
347 docstring const & BibTeXInfo::operator[](string const & field) const
348 {
349         return operator[](from_ascii(field));
350 }
351
352
353 docstring BibTeXInfo::getValueForKey(string const & key, 
354                 BibTeXInfo const * const xref) const
355 {
356         docstring const ret = operator[](key);
357         if (!ret.empty() || !xref)
358                 return ret;
359         return (*xref)[key];
360 }
361
362
363 //////////////////////////////////////////////////////////////////////
364 //
365 // BiblioInfo
366 //
367 //////////////////////////////////////////////////////////////////////
368
369 namespace {
370 // A functor for use with sort, leading to case insensitive sorting
371         class compareNoCase: public binary_function<docstring, docstring, bool>
372         {
373                 public:
374                         bool operator()(docstring const & s1, docstring const & s2) const {
375                                 return compare_no_case(s1, s2) < 0;
376                         }
377         };
378 } // namespace anon
379
380
381 vector<docstring> const BiblioInfo::getKeys() const
382 {
383         vector<docstring> bibkeys;
384         BiblioInfo::const_iterator it  = begin();
385         for (; it != end(); ++it)
386                 bibkeys.push_back(it->first);
387         sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
388         return bibkeys;
389 }
390
391
392 vector<docstring> const BiblioInfo::getFields() const
393 {
394         vector<docstring> bibfields;
395         set<docstring>::const_iterator it = field_names_.begin();
396         set<docstring>::const_iterator end = field_names_.end();
397         for (; it != end; ++it)
398                 bibfields.push_back(*it);
399         sort(bibfields.begin(), bibfields.end());
400         return bibfields;
401 }
402
403
404 vector<docstring> const BiblioInfo::getEntries() const
405 {
406         vector<docstring> bibentries;
407         set<docstring>::const_iterator it = entry_types_.begin();
408         set<docstring>::const_iterator end = entry_types_.end();
409         for (; it != end; ++it)
410                 bibentries.push_back(*it);
411         sort(bibentries.begin(), bibentries.end());
412         return bibentries;
413 }
414
415
416 docstring const BiblioInfo::getAbbreviatedAuthor(docstring const & key) const
417 {
418         BiblioInfo::const_iterator it = find(key);
419         if (it == end())
420                 return docstring();
421         BibTeXInfo const & data = it->second;
422         return data.getAbbreviatedAuthor();
423 }
424
425
426 docstring const BiblioInfo::getYear(docstring const & key) const
427 {
428         BiblioInfo::const_iterator it = find(key);
429         if (it == end())
430                 return docstring();
431         BibTeXInfo const & data = it->second;
432         docstring year = data.getYear();
433         if (!year.empty())
434                 return year;
435         // let's try the crossref
436         docstring const xref = data.getXRef();
437         if (xref.empty())
438                 return _("No year"); // no luck
439         BiblioInfo::const_iterator const xrefit = find(xref);
440         if (xrefit == end())
441                 return _("No year"); // no luck again
442         BibTeXInfo const & xref_data = xrefit->second;
443         return xref_data.getYear();
444         return data.getYear();
445 }
446
447
448 docstring const BiblioInfo::getInfo(docstring const & key) const
449 {
450         BiblioInfo::const_iterator it = find(key);
451         if (it == end())
452                 return docstring();
453         BibTeXInfo const & data = it->second;
454         BibTeXInfo const * xrefptr = 0;
455         docstring const xref = data.getXRef();
456         if (!xref.empty()) {
457                 BiblioInfo::const_iterator const xrefit = find(xref);
458                 if (xrefit != end())
459                         xrefptr = &(xrefit->second);
460         }
461         return data.getInfo(xrefptr);
462 }
463
464
465 vector<docstring> const BiblioInfo::getCiteStrings(
466         docstring const & key, Buffer const & buf) const
467 {
468         CiteEngine const engine = buf.params().citeEngine();
469         if (engine == ENGINE_BASIC || engine == ENGINE_NATBIB_NUMERICAL)
470                 return getNumericalStrings(key, buf);
471         else
472                 return getAuthorYearStrings(key, buf);
473 }
474
475
476 vector<docstring> const BiblioInfo::getNumericalStrings(
477         docstring const & key, Buffer const & buf) const
478 {
479         if (empty())
480                 return vector<docstring>();
481
482         docstring const author = getAbbreviatedAuthor(key);
483         docstring const year   = getYear(key);
484         if (author.empty() || year.empty())
485                 return vector<docstring>();
486
487         vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
488         
489         vector<docstring> vec(styles.size());
490         for (size_t i = 0; i != vec.size(); ++i) {
491                 docstring str;
492
493                 switch (styles[i]) {
494                         case CITE:
495                         case CITEP:
496                                 str = from_ascii("[#ID]");
497                                 break;
498
499                         case NOCITE:
500                                 str = _("Add to bibliography only.");
501                                 break;
502
503                         case CITET:
504                                 str = author + " [#ID]";
505                                 break;
506
507                         case CITEALT:
508                                 str = author + " #ID";
509                                 break;
510
511                         case CITEALP:
512                                 str = from_ascii("#ID");
513                                 break;
514
515                         case CITEAUTHOR:
516                                 str = author;
517                                 break;
518
519                         case CITEYEAR:
520                                 str = year;
521                                 break;
522
523                         case CITEYEARPAR:
524                                 str = '(' + year + ')';
525                                 break;
526                 }
527
528                 vec[i] = str;
529         }
530
531         return vec;
532 }
533
534
535 vector<docstring> const BiblioInfo::getAuthorYearStrings(
536         docstring const & key, Buffer const & buf) const
537 {
538         if (empty())
539                 return vector<docstring>();
540
541         docstring const author = getAbbreviatedAuthor(key);
542         docstring const year   = getYear(key);
543         if (author.empty() || year.empty())
544                 return vector<docstring>();
545
546         vector<CiteStyle> const & styles = citeStyles(buf.params().citeEngine());
547         
548         vector<docstring> vec(styles.size());
549         for (size_t i = 0; i != vec.size(); ++i) {
550                 docstring str;
551
552                 switch (styles[i]) {
553                         case CITE:
554                 // jurabib only: Author/Annotator
555                 // (i.e. the "before" field, 2nd opt arg)
556                                 str = author + "/<" + _("before") + '>';
557                                 break;
558
559                         case NOCITE:
560                                 str = _("Add to bibliography only.");
561                                 break;
562
563                         case CITET:
564                                 str = author + " (" + year + ')';
565                                 break;
566
567                         case CITEP:
568                                 str = '(' + author + ", " + year + ')';
569                                 break;
570
571                         case CITEALT:
572                                 str = author + ' ' + year ;
573                                 break;
574
575                         case CITEALP:
576                                 str = author + ", " + year ;
577                                 break;
578
579                         case CITEAUTHOR:
580                                 str = author;
581                                 break;
582
583                         case CITEYEAR:
584                                 str = year;
585                                 break;
586
587                         case CITEYEARPAR:
588                                 str = '(' + year + ')';
589                                 break;
590                 }
591                 vec[i] = str;
592         }
593         return vec;
594 }
595
596
597 void BiblioInfo::mergeBiblioInfo(BiblioInfo const & info)
598 {
599         bimap_.insert(info.begin(), info.end());
600 }
601
602
603 namespace {
604         // used in xhtml to sort a list of BibTeXInfo objects
605         bool lSorter(BibTeXInfo const * lhs, BibTeXInfo const * rhs)
606         {
607                 return lhs->getAbbreviatedAuthor() < rhs->getAbbreviatedAuthor();
608         }
609 }
610
611
612 void BiblioInfo::collectCitedEntries(Buffer const & buf)
613 {
614         cited_entries_.clear();
615         // We are going to collect all the citation keys used in the document,
616         // getting them from the TOC.
617         // FIXME We may want to collect these differently, in the first case,
618         // so that we might have them in order of appearance.
619         set<docstring> citekeys;
620         Toc const & toc = buf.tocBackend().toc("citation");
621         Toc::const_iterator it = toc.begin();
622         Toc::const_iterator const en = toc.end();
623         for (; it != en; ++it) {
624                 if (it->str().empty())
625                         continue;
626                 vector<docstring> const keys = getVectorFromString(it->str());
627                 citekeys.insert(keys.begin(), keys.end());
628         }
629         if (citekeys.empty())
630                 return;
631         
632         // We have a set of the keys used in this document.
633         // We will now convert it to a list of the BibTeXInfo objects used in 
634         // this document...
635         vector<BibTeXInfo const *> bi;
636         set<docstring>::const_iterator cit = citekeys.begin();
637         set<docstring>::const_iterator const cen = citekeys.end();
638         for (; cit != cen; ++cit) {
639                 BiblioInfo::const_iterator const bt = find(*cit);
640                 if (bt == end() || !bt->second.isBibTeX())
641                         continue;
642                 bi.push_back(&(bt->second));
643         }
644         // ...and sort it.
645         sort(bi.begin(), bi.end(), lSorter);
646         
647         // Now we can write the sorted keys
648         vector<BibTeXInfo const *>::const_iterator bit = bi.begin();
649         vector<BibTeXInfo const *>::const_iterator ben = bi.end();
650         for (; bit != ben; ++bit)
651                 cited_entries_.push_back((*bit)->key());
652 }
653
654
655 void BiblioInfo::makeCitationLabels(Buffer const & buf)
656 {
657         collectCitedEntries(buf);
658         // FIXME It'd be nice to do author-year as well as numerical
659         // and maybe even some other sorts of labels.
660         vector<docstring>::const_iterator it = cited_entries_.begin();
661         vector<docstring>::const_iterator const en = cited_entries_.end();
662         int keynumber = 0;
663         for (; it != en; ++it) {
664                 map<docstring, BibTeXInfo>::iterator const biit = bimap_.find(*it);
665                 // this shouldn't happen, but...
666                 if (biit == bimap_.end())
667                         continue;
668                 BibTeXInfo & entry = biit->second;
669                 docstring const key = convert<docstring>(++keynumber);
670                 entry.setCiteKey(key);
671         }
672 }
673
674
675 //////////////////////////////////////////////////////////////////////
676 //
677 // CitationStyle
678 //
679 //////////////////////////////////////////////////////////////////////
680
681 namespace {
682
683
684 char const * const citeCommands[] = {
685         "cite", "citet", "citep", "citealt", "citealp",
686         "citeauthor", "citeyear", "citeyearpar", "nocite" };
687
688 unsigned int const nCiteCommands =
689                 sizeof(citeCommands) / sizeof(char *);
690
691 CiteStyle const citeStylesArray[] = {
692         CITE, CITET, CITEP, CITEALT, CITEALP, 
693         CITEAUTHOR, CITEYEAR, CITEYEARPAR, NOCITE };
694
695 unsigned int const nCiteStyles =
696                 sizeof(citeStylesArray) / sizeof(CiteStyle);
697
698 CiteStyle const citeStylesFull[] = {
699         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
700
701 unsigned int const nCiteStylesFull =
702                 sizeof(citeStylesFull) / sizeof(CiteStyle);
703
704 CiteStyle const citeStylesUCase[] = {
705         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
706
707 unsigned int const nCiteStylesUCase =
708         sizeof(citeStylesUCase) / sizeof(CiteStyle);
709
710 } // namespace anon
711
712
713 CitationStyle citationStyleFromString(string const & command)
714 {
715         CitationStyle s;
716         if (command.empty())
717                 return s;
718
719         string cmd = command;
720         if (cmd[0] == 'C') {
721                 s.forceUpperCase = true;
722                 cmd[0] = 'c';
723         }
724
725         size_t const n = cmd.size() - 1;
726         if (cmd != "cite" && cmd[n] == '*') {
727                 s.full = true;
728                 cmd = cmd.substr(0, n);
729         }
730
731         char const * const * const last = citeCommands + nCiteCommands;
732         char const * const * const ptr = find(citeCommands, last, cmd);
733
734         if (ptr != last) {
735                 size_t idx = ptr - citeCommands;
736                 s.style = citeStylesArray[idx];
737         }
738         return s;
739 }
740
741
742 string citationStyleToString(const CitationStyle & s)
743 {
744         string cite = citeCommands[s.style];
745         if (s.full) {
746                 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
747                 if (std::find(citeStylesFull, last, s.style) != last)
748                         cite += '*';
749         }
750
751         if (s.forceUpperCase) {
752                 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
753                 if (std::find(citeStylesUCase, last, s.style) != last)
754                         cite[0] = 'C';
755         }
756
757         return cite;
758 }
759
760 vector<CiteStyle> citeStyles(CiteEngine engine)
761 {
762         unsigned int nStyles = 0;
763         unsigned int start = 0;
764
765         switch (engine) {
766                 case ENGINE_BASIC:
767                         nStyles = 2;
768                         start = 0;
769                         break;
770                 case ENGINE_NATBIB_AUTHORYEAR:
771                 case ENGINE_NATBIB_NUMERICAL:
772                         nStyles = nCiteStyles - 1;
773                         start = 1;
774                         break;
775                 case ENGINE_JURABIB:
776                         nStyles = nCiteStyles;
777                         start = 0;
778                         break;
779         }
780
781         vector<CiteStyle> styles(nStyles);
782         size_t i = 0;
783         int j = start;
784         for (; i != styles.size(); ++i, ++j)
785                 styles[i] = citeStylesArray[j];
786
787         return styles;
788 }
789
790 } // namespace lyx
791