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