]> git.lyx.org Git - lyx.git/blob - src/frontends/controllers/biblio.C
Don't call parseBibTeX at all if the info field is from lyx layout
[lyx.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())
246                 return string();
247         // is the entry a BibTeX one or one from lyx-layout "bibliography"?
248         if (!contains(it->second,'='))
249                 return it->second.c_str();
250
251         // Search for all possible "required" keys
252         string author = parseBibTeX(it->second, "author");
253         if (author.empty())
254                 author = parseBibTeX(it->second, "editor");
255
256         string year       = parseBibTeX(it->second, "year");
257         string title      = parseBibTeX(it->second, "title");
258         string booktitle  = parseBibTeX(it->second, "booktitle");
259         string chapter    = parseBibTeX(it->second, "chapter");
260         string number     = parseBibTeX(it->second, "number");
261         string volume     = parseBibTeX(it->second, "volume");
262         string pages      = parseBibTeX(it->second, "pages");
263
264         string media      = parseBibTeX(it->second, "journal");
265         if (media.empty())
266                 media = parseBibTeX(it->second, "publisher");
267         if (media.empty())
268                 media = parseBibTeX(it->second, "school");
269         if (media.empty())
270                 media = parseBibTeX(it->second, "institution");
271
272         ostringstream result;
273         if (!author.empty())
274                 result << author << ", ";
275         if (!title.empty())
276                 result << title;
277         if (!booktitle.empty())
278                 result << ", in " << booktitle;
279         if (!chapter.empty())
280                 result << ", Ch. " << chapter;
281         if (!media.empty())
282                 result << ", " << media;
283         if (!volume.empty())
284                 result << ", vol. " << volume;
285         if (!number.empty())
286                 result << ", no. " << number;
287         if (!pages.empty())
288                 result << ", pp. " << pages;
289         if (!year.empty())
290                 result << ", " << year;
291
292         char const * const tmp = result.str().c_str();
293         string result_str = tmp ? strip(tmp) : string();
294
295         if (result_str.empty())
296                 // This should never happen (or at least be very unusual!)
297                 result_str = it->second;
298
299         return result_str;
300 }
301  
302
303 vector<string>::const_iterator
304 searchKeys(InfoMap const & theMap,
305            vector<string> const & keys,
306            string const & expr,
307            vector<string>::const_iterator start,
308            Search type,
309            Direction dir,
310            bool caseSensitive)
311 {
312         // Preliminary checks
313         if (start < keys.begin() || start >= keys.end())
314                 return keys.end();
315         
316         string search_expr = frontStrip(strip(expr));
317         if (search_expr.empty())
318                 return keys.end();
319
320         if (type == SIMPLE)
321                 return simpleSearch(theMap, keys, search_expr, start, dir,
322                                     caseSensitive);
323
324         return regexSearch(theMap, keys, search_expr, start, dir);
325 }
326
327
328 string const parseBibTeX(string data, string const & findkey)
329 {
330         string keyvalue;
331         // at first we delete all characters right of '%' and
332         // replace tabs through a space and remove leading spaces
333         string data_;
334         int Entries = 0;
335         string dummy = token(data,'\n', Entries);
336         while (!dummy.empty()) {
337                 dummy = subst(dummy, '\t', ' ');        // no tabs
338                 dummy = frontStrip(dummy);      // no leading spaces
339                 string::size_type const idx =
340                         dummy.empty() ? string::npos : dummy.find('%');
341                 if (idx != string::npos) {
342                         if (idx > 0) {
343                                 // This is safe. data MUST contain a '%'
344                                 data_ += dummy.substr(0,data.find('%'));
345                         }
346                 } else {
347                         data_ += dummy;
348                 }
349                 dummy = token(data, '\n', ++Entries);
350         }
351         data = data_;
352
353         // unlikely!
354         if (data.empty())
355                 return string();
356
357         // now get only the important line of the bibtex entry.
358         // all entries are devided by ',' except the last one.  
359         data += ',';  // now we have same behaviour for all entries
360                       // because the last one is "blah ... }"
361         Entries = 0;                    
362         dummy = token(data, ',', Entries);
363         while (!contains(lowercase(dummy), findkey) && !dummy.empty())
364                 dummy = token(data, ',', ++Entries);
365         if (dummy.empty())
366                 return string();                        // no such keyword
367         // we are not sure, if we get all, because "key= "blah, blah" is allowed.
368         // therefore we read all until the next "=" character, which follows a
369         // new keyword
370         keyvalue = dummy;
371         dummy = token(data, ',', ++Entries);
372         while (!contains(dummy, '=') && !dummy.empty()) {
373                 keyvalue += (',' + dummy);
374                 dummy = token(data, ',', ++Entries);
375         }
376         data = keyvalue;                // now we have the important line       
377         data = strip(data, ' ');                // all spaces
378         if (!contains(data, '{'))       // no opening '{'
379                 data = strip(data, '}');// maybe there is a main closing '}'
380         // happens, when last keyword
381         string::size_type const idx =
382                 data.empty() ? data.find('=') : string::npos;
383
384         if (idx == string::npos)
385                 return string();
386
387         data = data.substr(idx, data.length() - 1);
388         data = frontStrip(strip(data));
389
390         if (data.length() < 2 || data[0] != '=') {      // a valid entry?
391                 return string();
392         } else {
393                 data = frontStrip(data.substr(1, data.length() - 1));
394                 if (data.length() < 2) {
395                         return data;    // not long enough to find delimiters
396                 } else {
397                         string::size_type keypos = 1;
398                         char enclosing;
399                         if (data[0] == '{') {
400                                 enclosing = '}';
401                         } else if (data[0] == '"') {
402                                 enclosing = '"';
403                         } else {
404                                 return data;    // no {} and no "", pure data
405                         }
406                         string tmp = data.substr(keypos, data.length()-1);
407                         while (tmp.find('{') != string::npos &&
408                                tmp.find('}') != string::npos &&
409                                tmp.find('{') < tmp.find('}') &&
410                                tmp.find('{') < tmp.find(enclosing)) {
411                                 
412                                 keypos += tmp.find('{') + 1;
413                                 tmp = data.substr(keypos, data.length() - 1);
414                                 keypos += tmp.find('}') + 1;
415                                 tmp = data.substr(keypos, data.length() - 1);
416                         }
417                         if (tmp.find(enclosing) == string::npos)
418                                 return data;
419                         else {
420                                 keypos += tmp.find(enclosing);
421                                 return data.substr(1, keypos - 1);
422                         }
423                 }
424         }
425 }
426
427
428 CitationStyle const getCitationStyle(string const & command)
429 {
430         if (command.empty()) return CitationStyle();
431     
432         CitationStyle cs;
433         string cmd = command;
434
435         if (cmd[0] == 'C') {
436                 cs.forceUCase = true;
437                 cmd[0] = 'c';
438         }
439
440         size_t n = cmd.size()-1;
441         if (cmd[n] == '*') {
442                 cs.full = true;
443                 cmd = cmd.substr(0,n);
444         }
445
446         char const * const * const last = citeCommands + nCiteCommands;
447         char const * const * const ptr = std::find(citeCommands, last, cmd);
448
449         if (ptr != last) {
450                 size_t idx = ptr - citeCommands;
451                 cs.style = citeStyles[idx];
452         }
453
454         return cs;
455 }
456
457
458 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
459 {
460         string cite = citeCommands[command];
461         if (full) {
462                 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
463                 if (std::find(citeStylesFull, last, command) != last)
464                         cite += "*";
465         }
466
467         if (forceUCase) {
468                 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
469                 if (std::find(citeStylesUCase, last, command) != last)
470                         cite[0] = 'C';
471         }
472
473         return cite;
474 }
475
476         
477 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
478 {
479         unsigned int nStyles = 1;
480         unsigned int start = 0;
481         if (usingNatbib) {
482                 nStyles = nCiteStyles - 1;
483                 start = 1;
484         }
485
486         vector<CiteStyle> styles(nStyles);
487
488         vector<CiteStyle>::size_type i = 0;
489         int j = start;
490         for (; i != styles.size(); ++i, ++j) {
491                 styles[i] = citeStyles[j];
492         }
493
494         return styles;
495 }
496
497
498 vector<string> const
499 getNumericalStrings(string const & key,
500                     InfoMap const & map, vector<CiteStyle> const & styles)
501 {
502         if (map.empty()) {
503                 vector<string> vec(1);
504                 vec[0] = _("No database");
505                 return vec;
506         }
507         
508         vector<string> vec(styles.size());
509
510         string const author = getAbbreviatedAuthor(map, key);
511         string const year   = getYear(map, key);
512         
513         for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
514                 string str;
515
516                 switch (styles[i]) {
517                 case CITE:
518                 case CITEP:
519                         str = "[#ID]";
520                         break;
521                         
522                 case CITET:
523                         str = author + " [#ID]";
524                         break;
525                         
526                 case CITEALT:
527                         str = author + " #ID";
528                         break;
529                         
530                 case CITEALP:
531                         str = "#ID";
532                         break;
533                         
534                 case CITEAUTHOR:
535                         str = author;
536                         break;
537                         
538                 case CITEYEAR:
539                         str = year;
540                         break;
541                         
542                 case CITEYEARPAR:
543                         str = "(" + year + ")";
544                         break;
545                 }
546
547                 vec[i] = str;
548         }
549         
550         return vec;
551 }
552
553
554 vector<string> const
555 getAuthorYearStrings(string const & key,
556                     InfoMap const & map, vector<CiteStyle> const & styles)
557 {
558         if (map.empty()) {
559                 vector<string> vec(1);
560                 vec[0] = _("No database");
561                 return vec;
562         }
563         
564         vector<string> vec(styles.size());
565
566         string const author = getAbbreviatedAuthor(map, key);
567         string const year   = getYear(map, key);
568         
569         for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
570                 string str;
571
572                 switch (styles[i]) {
573                 case CITET:
574                         str = author + " (" + year + ")";
575                         break;
576                         
577                 case CITE:
578                 case CITEP:
579                         str = "(" + author + ", " + year + ")";
580                         break;
581                         
582                 case CITEALT:
583                         str = author + " " + year ;
584                         break;
585                         
586                 case CITEALP:
587                         str = author + ", " + year ;
588                         break;
589                         
590                 case CITEAUTHOR:
591                         str = author;
592                         break;
593                         
594                 case CITEYEAR:
595                         str = year;
596                         break;
597                         
598                 case CITEYEARPAR:
599                         str = "(" + year + ")";
600                         break;
601                 }
602
603                 vec[i] = str;
604         }
605         
606         return vec;
607 }
608
609 } // namespace biblio