]> git.lyx.org Git - lyx.git/blob - src/frontends/controllers/biblio.C
Overhaul the branches code.
[lyx.git] / src / frontends / controllers / biblio.C
1 /**
2  * \file biblio.C
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  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "biblio.h"
15
16 #include "support/std_sstream.h"
17 #include "gettext.h" // for _()
18
19 #include "support/lstrings.h"
20
21 #include <boost/regex.hpp>
22
23 #include <algorithm>
24
25 using lyx::support::ascii_lowercase;
26 using lyx::support::bformat;
27 using lyx::support::compare_ascii_no_case;
28 using lyx::support::contains;
29 using lyx::support::getVectorFromString;
30 using lyx::support::ltrim;
31 using lyx::support::rtrim;
32 using lyx::support::split;
33 using lyx::support::subst;
34 using lyx::support::token;
35 using lyx::support::trim;
36
37 using std::string;
38 using std::ostringstream;
39 using std::vector;
40
41
42 namespace biblio {
43
44 string const familyName(string const & name)
45 {
46         // Very simple parser
47         string fname = name;
48
49         // possible authorname combinations are:
50         // "Surname, FirstName"
51         // "Surname, F."
52         // "FirstName Surname"
53         // "F. Surname"
54         string::size_type idx = fname.find(',');
55         if (idx != string::npos)
56                 return ltrim(fname.substr(0, idx));
57         idx = fname.rfind('.');
58         if (idx != string::npos)
59                 fname = ltrim(fname.substr(idx + 1));
60         // test if we have a LaTeX Space in front
61         if (fname[0] == '\\')
62                 return fname.substr(2);
63
64         return rtrim(fname);
65 }
66
67
68 string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
69 {
70         BOOST_ASSERT(!map.empty());
71
72         InfoMap::const_iterator it = map.find(key);
73         if (it == map.end())
74                 return string();
75         string const & data = it->second;
76
77         // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
78         string::size_type const pos = data.find("TheBibliographyRef");
79         if (pos != string::npos) {
80                 if (pos <= 2) {
81                         return string();
82                 }
83
84                 string const opt = trim(data.substr(0, pos - 1));
85                 if (opt.empty())
86                         return string();
87
88                 string authors;
89                 split(opt, authors, '(');
90                 return authors;
91         }
92
93         string author = parseBibTeX(data, "author");
94
95         if (author.empty())
96                 author = parseBibTeX(data, "editor");
97
98         if (author.empty()) {
99                 author = parseBibTeX(data, "key");
100                 if (author.empty())
101                         author = key;
102                 return author;
103         }
104
105         vector<string> const authors = getVectorFromString(author, " and ");
106         if (authors.empty())
107                 return author;
108
109         if (authors.size() == 2)
110                 return bformat(_("%1$s and %2$s"),
111                         familyName(authors[0]), familyName(authors[1]));
112
113         if (authors.size() > 2)
114                 return bformat(_("%1$s et al."), familyName(authors[0]));
115
116         return familyName(authors[0]);
117 }
118
119
120 string const getYear(InfoMap const & map, string const & key)
121 {
122         BOOST_ASSERT(!map.empty());
123
124         InfoMap::const_iterator it = map.find(key);
125         if (it == map.end())
126                 return string();
127         string const & data = it->second;
128
129         // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
130         string::size_type const pos = data.find("TheBibliographyRef");
131         if (pos != string::npos) {
132                 if (pos <= 2) {
133                         return string();
134                 }
135
136                 string const opt =
137                         trim(data.substr(0, pos - 1));
138                 if (opt.empty())
139                         return string();
140
141                 string authors;
142                 string const tmp = split(opt, authors, '(');
143                 string year;
144                 split(tmp, year, ')');
145                 return year;
146
147         }
148
149         string year = parseBibTeX(data, "year");
150         if (year.empty())
151                 year = _("No year");
152
153         return year;
154 }
155
156
157 namespace {
158
159 // A functor for use with std::sort, leading to case insensitive sorting
160 struct compareNoCase: public std::binary_function<string, string, bool>
161 {
162         bool operator()(string const & s1, string const & s2) const {
163                 return compare_ascii_no_case(s1, s2) < 0;
164         }
165 };
166
167 } // namespace anon
168
169
170 vector<string> const getKeys(InfoMap const & map)
171 {
172         vector<string> bibkeys;
173         InfoMap::const_iterator it  = map.begin();
174         InfoMap::const_iterator end = map.end();
175         for (; it != end; ++it) {
176                 bibkeys.push_back(it->first);
177         }
178
179         std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
180         return bibkeys;
181 }
182
183
184 string const getInfo(InfoMap const & map, string const & key)
185 {
186         BOOST_ASSERT(!map.empty());
187
188         InfoMap::const_iterator it = map.find(key);
189         if (it == map.end())
190                 return string();
191         string const & data = it->second;
192
193         // is the entry a BibTeX one or one from lyx-layout "bibliography"?
194         string const separator("TheBibliographyRef");
195         string::size_type const pos = data.find(separator);
196         if (pos != string::npos) {
197                 string::size_type const pos2 = pos + separator.size();
198                 string const info = trim(data.substr(pos2));
199                 return info;
200         }
201
202         // Search for all possible "required" keys
203         string author = parseBibTeX(data, "author");
204         if (author.empty())
205                 author = parseBibTeX(data, "editor");
206
207         string year       = parseBibTeX(data, "year");
208         string title      = parseBibTeX(data, "title");
209         string booktitle  = parseBibTeX(data, "booktitle");
210         string chapter    = parseBibTeX(data, "chapter");
211         string number     = parseBibTeX(data, "number");
212         string volume     = parseBibTeX(data, "volume");
213         string pages      = parseBibTeX(data, "pages");
214
215         string media      = parseBibTeX(data, "journal");
216         if (media.empty())
217                 media = parseBibTeX(data, "publisher");
218         if (media.empty())
219                 media = parseBibTeX(data, "school");
220         if (media.empty())
221                 media = parseBibTeX(data, "institution");
222
223         ostringstream result;
224         if (!author.empty())
225                 result << author << ", ";
226         if (!title.empty())
227                 result << title;
228         if (!booktitle.empty())
229                 result << ", in " << booktitle;
230         if (!chapter.empty())
231                 result << ", Ch. " << chapter;
232         if (!media.empty())
233                 result << ", " << media;
234         if (!volume.empty())
235                 result << ", vol. " << volume;
236         if (!number.empty())
237                 result << ", no. " << number;
238         if (!pages.empty())
239                 result << ", pp. " << pages;
240         if (!year.empty())
241                 result << ", " << year;
242
243         string const result_str = rtrim(result.str());
244         if (!result_str.empty())
245                 return result_str;
246
247         // This should never happen (or at least be very unusual!)
248         return data;
249 }
250
251
252 namespace {
253
254 // Escape special chars.
255 // All characters are literals except: '.|*?+(){}[]^$\'
256 // These characters are literals when preceded by a "\", which is done here
257 string const escape_special_chars(string const & expr)
258 {
259         // Search for all chars '.|*?+(){}[^$]\'
260         // Note that '[' and '\' must be escaped.
261         // This is a limitation of boost::regex, but all other chars in BREs
262         // are assumed literal.
263         boost::RegEx reg("[].|*?+(){}^$\\[\\\\]");
264
265         // $& is a perl-like expression that expands to all of the current match
266         // The '$' must be prefixed with the escape character '\' for
267         // boost to treat it as a literal.
268         // Thus, to prefix a matched expression with '\', we use:
269         return reg.Merge(expr, "\\\\$&");
270 }
271
272
273 // A functor for use with std::find_if, used to ascertain whether a
274 // data entry matches the required regex_
275 struct RegexMatch
276 {
277         // re and icase are used to construct an instance of boost::RegEx.
278         // if icase is true, then matching is insensitive to case
279         RegexMatch(InfoMap const & m, string const & re, bool icase)
280                 : map_(m), regex_(re, icase) {}
281
282         bool operator()(string const & key) {
283                 if (!validRE())
284                         return false;
285
286                 // the data searched is the key + its associated BibTeX/biblio
287                 // fields
288                 string data = key;
289                 InfoMap::const_iterator info = map_.find(key);
290                 if (info != map_.end())
291                         data += ' ' + info->second;
292
293                 // Attempts to find a match for the current RE
294                 // somewhere in data.
295                 return regex_.Search(data);
296         }
297
298         bool validRE() const { return regex_.error_code() == 0; }
299
300 private:
301         InfoMap const map_;
302         boost::RegEx regex_;
303 };
304
305 } // namespace anon
306
307
308 vector<string>::const_iterator
309 searchKeys(InfoMap const & theMap,
310            vector<string> const & keys,
311            string const & search_expr,
312            vector<string>::const_iterator start,
313            Search type,
314            Direction dir,
315            bool caseSensitive)
316 {
317         // Preliminary checks
318         if (start < keys.begin() || start >= keys.end())
319                 return keys.end();
320
321         string expr = trim(search_expr);
322         if (expr.empty())
323                 return keys.end();
324
325         if (type == SIMPLE)
326                 // We must escape special chars in the search_expr so that
327                 // it is treated as a simple string by boost::regex.
328                 expr = escape_special_chars(expr);
329
330         // Build the functor that will be passed to find_if.
331         RegexMatch const match(theMap, expr, !caseSensitive);
332         if (!match.validRE())
333                 return keys.end();
334
335         // Search the vector of 'keys' from 'start' for one that matches the
336         // predicate 'match'. Searching can be forward or backward from start.
337         if (dir == FORWARD)
338                 return std::find_if(start, keys.end(), match);
339
340         vector<string>::const_reverse_iterator rit(start);
341         vector<string>::const_reverse_iterator rend = keys.rend();
342         rit = std::find_if(rit, rend, match);
343
344         if (rit == rend)
345                 return keys.end();
346         // This is correct and always safe.
347         // (See Meyer's Effective STL, Item 28.)
348         return (++rit).base();
349 }
350
351
352 string const parseBibTeX(string data, string const & findkey)
353 {
354         string keyvalue;
355         // at first we delete all characters right of '%' and
356         // replace tabs through a space and remove leading spaces
357         // we read the data line by line so that the \n are
358         // ignored, too.
359         string data_;
360         int Entries = 0;
361         string dummy = token(data,'\n', Entries);
362         while (!dummy.empty()) {
363                 dummy = subst(dummy, '\t', ' ');        // no tabs
364                 dummy = ltrim(dummy);           // no leading spaces
365                 // ignore lines with a beginning '%' or ignore all right of %
366                 string::size_type const idx =
367                         dummy.empty() ? string::npos : dummy.find('%');
368                 if (idx != string::npos)
369                         dummy.erase(idx, string::npos);
370                 // do we have a new token or a new line of
371                 // the same one? In the first case we ignore
372                 // the \n and in the second we replace it
373                 // with a space
374                 if (!dummy.empty()) {
375                         if (!contains(dummy, "="))
376                                 data_ += ' ' + dummy;
377                         else
378                                 data_ += dummy;
379                 }
380                 dummy = token(data, '\n', ++Entries);
381         }
382
383         // replace double commas with "" for easy scanning
384         data = subst(data_, ",,", "\"\"");
385
386         // unlikely!
387         if (data.empty())
388                 return string();
389
390         // now get only the important line of the bibtex entry.
391         // all entries are devided by ',' except the last one.
392         data += ',';  // now we have same behaviour for all entries
393                       // because the last one is "blah ... }"
394         Entries = 0;
395         bool found = false;
396         // parsing of title and booktitle is different from the
397         // others, because booktitle contains title
398         do {
399                 dummy = token(data, ',', Entries++);
400                 if (!dummy.empty()) {
401                         found = contains(ascii_lowercase(dummy), findkey);
402                         if (findkey == "title" &&
403                                 contains(ascii_lowercase(dummy), "booktitle"))
404                                 found = false;
405                 }
406         } while (!found && !dummy.empty());
407         if (dummy.empty())
408                 // no such keyword
409                 return string();
410
411         // we are not sure, if we get all, because "key= "blah, blah" is
412         // allowed.
413         // Therefore we read all until the next "=" character, which follows a
414         // new keyword
415         keyvalue = dummy;
416         dummy = token(data, ',', Entries++);
417         while (!contains(dummy, '=') && !dummy.empty()) {
418                 keyvalue += ',' + dummy;
419                 dummy = token(data, ',', Entries++);
420         }
421
422         // replace double "" with originals ,, (two commas)
423         // leaving us with the all-important line
424         data = subst(keyvalue, "\"\"", ",,");
425
426         // Clean-up.
427         // 1. Spaces
428         data = rtrim(data);
429         // 2. if there is no opening '{' then a closing '{' is probably cruft.
430         if (!contains(data, '{'))
431                 data = rtrim(data, "}");
432         // happens, when last keyword
433         string::size_type const idx =
434                 !data.empty() ? data.find('=') : string::npos;
435
436         if (idx == string::npos)
437                 return string();
438
439         data = trim(data.substr(idx));
440
441         if (data.length() < 2 || data[0] != '=') {      // a valid entry?
442                 return string();
443         } else {
444                 // delete '=' and the following spaces
445                 data = ltrim(data, " =");
446                 if (data.length() < 2) {
447                         return data;    // not long enough to find delimiters
448                 } else {
449                         string::size_type keypos = 1;
450                         char enclosing;
451                         if (data[0] == '{') {
452                                 enclosing = '}';
453                         } else if (data[0] == '"') {
454                                 enclosing = '"';
455                         } else {
456                                 // no {} and no "", pure data but with a
457                                 // possible ',' at the end
458                                 return rtrim(data, ",");
459                         }
460                         string tmp = data.substr(keypos);
461                         while (tmp.find('{') != string::npos &&
462                                tmp.find('}') != string::npos &&
463                                tmp.find('{') < tmp.find('}') &&
464                                tmp.find('{') < tmp.find(enclosing)) {
465
466                                 keypos += tmp.find('{') + 1;
467                                 tmp = data.substr(keypos);
468                                 keypos += tmp.find('}') + 1;
469                                 tmp = data.substr(keypos);
470                         }
471                         if (tmp.find(enclosing) == string::npos)
472                                 return data;
473                         else {
474                                 keypos += tmp.find(enclosing);
475                                 return data.substr(1, keypos - 1);
476                         }
477                 }
478         }
479 }
480
481
482 namespace {
483
484
485 char const * const citeCommands[] = {
486         "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
487         "citeyear", "citeyearpar" };
488
489 unsigned int const nCiteCommands =
490         sizeof(citeCommands) / sizeof(char *);
491
492 CiteStyle const citeStyles[] = {
493         CITE, CITET, CITEP, CITEALT, CITEALP,
494         CITEAUTHOR, CITEYEAR, CITEYEARPAR };
495
496 unsigned int const nCiteStyles =
497         sizeof(citeStyles) / sizeof(CiteStyle);
498
499 CiteStyle const citeStylesFull[] = {
500         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
501
502 unsigned int const nCiteStylesFull =
503         sizeof(citeStylesFull) / sizeof(CiteStyle);
504
505 CiteStyle const citeStylesUCase[] = {
506         CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
507
508 unsigned int const nCiteStylesUCase =
509         sizeof(citeStylesUCase) / sizeof(CiteStyle);
510
511 } // namespace anon
512
513
514 CitationStyle const getCitationStyle(string const & command)
515 {
516         if (command.empty()) return CitationStyle();
517
518         CitationStyle cs;
519         string cmd = command;
520
521         if (cmd[0] == 'C') {
522                 cs.forceUCase = true;
523                 cmd[0] = 'c';
524         }
525
526         size_t n = cmd.size() - 1;
527         if (cmd[n] == '*') {
528                 cs.full = true;
529                 cmd = cmd.substr(0,n);
530         }
531
532         char const * const * const last = citeCommands + nCiteCommands;
533         char const * const * const ptr = std::find(citeCommands, last, cmd);
534
535         if (ptr != last) {
536                 size_t idx = ptr - citeCommands;
537                 cs.style = citeStyles[idx];
538         }
539
540         return cs;
541 }
542
543
544 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
545 {
546         string cite = citeCommands[command];
547         if (full) {
548                 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
549                 if (std::find(citeStylesFull, last, command) != last)
550                         cite += '*';
551         }
552
553         if (forceUCase) {
554                 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
555                 if (std::find(citeStylesUCase, last, command) != last)
556                         cite[0] = 'C';
557         }
558
559         return cite;
560 }
561
562
563 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
564 {
565         unsigned int nStyles = 1;
566         unsigned int start = 0;
567         if (usingNatbib) {
568                 nStyles = nCiteStyles - 1;
569                 start = 1;
570         }
571
572         vector<CiteStyle> styles(nStyles);
573
574         vector<CiteStyle>::size_type i = 0;
575         int j = start;
576         for (; i != styles.size(); ++i, ++j) {
577                 styles[i] = citeStyles[j];
578         }
579
580         return styles;
581 }
582
583
584 vector<string> const
585 getNumericalStrings(string const & key,
586                     InfoMap const & map, vector<CiteStyle> const & styles)
587 {
588         if (map.empty()) {
589                 return vector<string>();
590         }
591
592         string const author = getAbbreviatedAuthor(map, key);
593         string const year   = getYear(map, key);
594         if (author.empty() || year.empty())
595                 return vector<string>();
596
597         vector<string> vec(styles.size());
598         for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
599                 string str;
600
601                 switch (styles[i]) {
602                 case CITE:
603                 case CITEP:
604                         str = "[#ID]";
605                         break;
606
607                 case CITET:
608                         str = author + " [#ID]";
609                         break;
610
611                 case CITEALT:
612                         str = author + " #ID";
613                         break;
614
615                 case CITEALP:
616                         str = "#ID";
617                         break;
618
619                 case CITEAUTHOR:
620                         str = author;
621                         break;
622
623                 case CITEYEAR:
624                         str = year;
625                         break;
626
627                 case CITEYEARPAR:
628                         str = '(' + year + ')';
629                         break;
630                 }
631
632                 vec[i] = str;
633         }
634
635         return vec;
636 }
637
638
639 vector<string> const
640 getAuthorYearStrings(string const & key,
641                     InfoMap const & map, vector<CiteStyle> const & styles)
642 {
643         if (map.empty()) {
644                 return vector<string>();
645         }
646
647         string const author = getAbbreviatedAuthor(map, key);
648         string const year   = getYear(map, key);
649         if (author.empty() || year.empty())
650                 return vector<string>();
651
652         vector<string> vec(styles.size());
653         for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
654                 string str;
655
656                 switch (styles[i]) {
657                 case CITE:
658                 case CITET:
659                         str = author + " (" + year + ')';
660                         break;
661
662                 case CITEP:
663                         str = '(' + author + ", " + year + ')';
664                         break;
665
666                 case CITEALT:
667                         str = author + ' ' + year ;
668                         break;
669
670                 case CITEALP:
671                         str = author + ", " + year ;
672                         break;
673
674                 case CITEAUTHOR:
675                         str = author;
676                         break;
677
678                 case CITEYEAR:
679                         str = year;
680                         break;
681
682                 case CITEYEARPAR:
683                         str = '(' + year + ')';
684                         break;
685                 }
686
687                 vec[i] = str;
688         }
689
690         return vec;
691 }
692
693 } // namespace biblio