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