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