]> git.lyx.org Git - lyx.git/blob - src/frontends/controllers/biblio.C
ccbc6cdfc515a9bce01bd7c14ac9f29a0be8d7a1
[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
146 } // namespace anon
147
148
149 string const familyName(string const & name)
150 {
151         // Very simple parser
152         string fname = name;
153
154         // possible authorname combinations are:
155         // "Surname, FirstName"
156         // "Surname, F."
157         // "FirstName Surname"
158         // "F. Surname"
159         string::size_type idx = fname.find(",");
160         if (idx != string::npos)
161                 return frontStrip(fname.substr(0,idx));
162         idx = fname.rfind(".");
163         if (idx != string::npos)
164                 fname = frontStrip(fname.substr(idx+1));
165         // test if we have a LaTeX Space in front
166         if (fname[0] == '\\')
167                 return fname.substr(2);
168
169         return fname;
170 }
171
172
173 string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
174 {
175         lyx::Assert(!map.empty());
176
177         InfoMap::const_iterator it = map.find(key);
178         if (it == map.end())
179                 return string();
180
181         string::size_type const pos = it->second.find("TheBibliographyRef");
182         if (pos != string::npos) {
183                 if (pos <= 2) {
184                         return string();
185                 }
186
187                 string const opt =
188                         strip(frontStrip(it->second.substr(0, pos-1)));
189                 if (opt.empty())
190                         return string();
191
192                 string authors;
193                 split(opt, authors, '(');
194                 return authors;
195         }
196
197         string author = parseBibTeX(it->second, "author");
198         if (author.empty())
199                 author = parseBibTeX(it->second, "editor");
200
201         if (author.empty()) {
202                 author = parseBibTeX(it->second, "key");
203                 if (author.empty())
204                         author = key;
205                 return author;
206         }
207
208         vector<string> authors = getVectorFromString(author, "and");
209
210         if (!authors.empty()) {
211                 author.erase();
212
213                 for (vector<string>::iterator it = authors.begin();
214                      it != authors.end(); ++it) {
215                         *it = familyName(strip(*it));
216                 }
217
218                 author = authors[0];
219                 if (authors.size() == 2)
220                         author += _(" and ") + authors[1];
221                 else if (authors.size() > 2)
222                         author += _(" et al.");
223         }
224
225         return author;
226 }
227
228
229 string const getYear(InfoMap const & map, string const & key)
230 {
231         lyx::Assert(!map.empty());
232
233         InfoMap::const_iterator it = map.find(key);
234         if (it == map.end())
235                 return string();
236
237         string::size_type const pos = it->second.find("TheBibliographyRef");
238         if (pos != string::npos) {
239                 if (pos <= 2) {
240                         return string();
241                 }
242
243                 string const opt =
244                         strip(frontStrip(it->second.substr(0, pos-1)));
245                 if (opt.empty())
246                         return string();
247
248                 string authors;
249                 string const tmp = split(opt, authors, '(');
250                 string year;
251                 split(tmp, year, ')');
252                 return year;
253
254         }
255
256         string year = parseBibTeX(it->second, "year");
257         if (year.empty())
258                 year = _("No year");
259
260         return year;
261 }
262
263
264 // A functor for use with std::sort, leading to case insensitive sorting
265 struct compareNoCase: public std::binary_function<string, string, bool>
266 {
267         bool operator()(string const & s1, string const & s2) const {
268                 return compare_no_case(s1, s2) < 0;
269         }
270 };
271
272 vector<string> const getKeys(InfoMap const & map)
273 {
274         vector<string> bibkeys;
275
276         for (InfoMap::const_iterator it = map.begin(); it != map.end(); ++it) {
277                 bibkeys.push_back(it->first);
278         }
279
280         sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
281         return bibkeys;
282 }
283
284
285 string const getInfo(InfoMap const & map, string const & key)
286 {
287         lyx::Assert(!map.empty());
288
289         InfoMap::const_iterator it = map.find(key);
290         if (it == map.end())
291                 return string();
292
293         // is the entry a BibTeX one or one from lyx-layout "bibliography"?
294         string const separator("TheBibliographyRef");
295         string::size_type const pos = it->second.find(separator);
296         if (pos != string::npos) {
297                 string::size_type const pos2 = pos + separator.size();
298                 string const info = strip(frontStrip(it->second.substr(pos2)));
299                 return info;
300         }
301
302         // Search for all possible "required" keys
303         string author = parseBibTeX(it->second, "author");
304         if (author.empty())
305                 author = parseBibTeX(it->second, "editor");
306
307         string year       = parseBibTeX(it->second, "year");
308         string title      = parseBibTeX(it->second, "title");
309         string booktitle  = parseBibTeX(it->second, "booktitle");
310         string chapter    = parseBibTeX(it->second, "chapter");
311         string number     = parseBibTeX(it->second, "number");
312         string volume     = parseBibTeX(it->second, "volume");
313         string pages      = parseBibTeX(it->second, "pages");
314
315         string media      = parseBibTeX(it->second, "journal");
316         if (media.empty())
317                 media = parseBibTeX(it->second, "publisher");
318         if (media.empty())
319                 media = parseBibTeX(it->second, "school");
320         if (media.empty())
321                 media = parseBibTeX(it->second, "institution");
322
323         ostringstream result;
324         if (!author.empty())
325                 result << author << ", ";
326         if (!title.empty())
327                 result << title;
328         if (!booktitle.empty())
329                 result << ", in " << booktitle;
330         if (!chapter.empty())
331                 result << ", Ch. " << chapter;
332         if (!media.empty())
333                 result << ", " << media;
334         if (!volume.empty())
335                 result << ", vol. " << volume;
336         if (!number.empty())
337                 result << ", no. " << number;
338         if (!pages.empty())
339                 result << ", pp. " << pages;
340         if (!year.empty())
341                 result << ", " << year;
342
343         string const result_str = strip(result.str().c_str());
344         if (!result_str.empty())
345                 return result_str;
346
347         // This should never happen (or at least be very unusual!)
348         return it->second;
349 }
350
351
352 vector<string>::const_iterator
353 searchKeys(InfoMap const & theMap,
354            vector<string> const & keys,
355            string const & expr,
356            vector<string>::const_iterator start,
357            Search type,
358            Direction dir,
359            bool caseSensitive)
360 {
361         // Preliminary checks
362         if (start < keys.begin() || start >= keys.end())
363                 return keys.end();
364
365         string search_expr = frontStrip(strip(expr));
366         if (search_expr.empty())
367                 return keys.end();
368
369         if (type == SIMPLE)
370                 return simpleSearch(theMap, keys, search_expr, start, dir,
371                                     caseSensitive);
372
373         return regexSearch(theMap, keys, search_expr, start, dir);
374 }
375
376
377 string const parseBibTeX(string data, string const & findkey)
378 {
379         string keyvalue;
380         // at first we delete all characters right of '%' and
381         // replace tabs through a space and remove leading spaces
382         string data_;
383         int Entries = 0;
384         string dummy = token(data,'\n', Entries);
385         while (!dummy.empty()) {
386                 dummy = subst(dummy, '\t', ' ');        // no tabs
387                 dummy = frontStrip(dummy);      // no leading spaces
388                 string::size_type const idx =
389                         dummy.empty() ? string::npos : dummy.find('%');
390                 if (idx != string::npos) {
391                         // ignore lines with a beginning '%'
392                         if (idx > 0) {
393                                 data_ += dummy.substr(0,data.find('%'));
394                         }
395                 } else {
396                         data_ += dummy;
397                 }
398                 dummy = token(data, '\n', ++Entries);
399         }
400         // replace double commas with "" for easy scanning
401         data = subst(data_, ",,", "\"\"");
402
403         // unlikely!
404         if (data.empty())
405                 return string();
406
407         // now get only the important line of the bibtex entry.
408         // all entries are devided by ',' except the last one.
409         data += ',';  // now we have same behaviour for all entries
410                       // because the last one is "blah ... }"
411         Entries = 0;
412         dummy = token(data, ',', Entries);
413         while (!contains(lowercase(dummy), findkey) && !dummy.empty())
414                 dummy = token(data, ',', ++Entries);
415         if (dummy.empty())
416                 // no such keyword
417                 return string();
418
419         // we are not sure, if we get all, because "key= "blah, blah" is
420         // allowed.
421         // Therefore we read all until the next "=" character, which follows a
422         // new keyword
423         keyvalue = dummy;
424         dummy = token(data, ',', ++Entries);
425         while (!contains(dummy, '=') && !dummy.empty()) {
426                 keyvalue += (',' + dummy);
427                 dummy = token(data, ',', ++Entries);
428         }
429
430         // replace double "" with originals ,, (two commas)
431         // leaving us with the all-important line
432         data = subst(keyvalue, "\"\"", ",,");
433
434         // Clean-up.
435         // 1. Spaces
436         data = strip(data, ' ');
437         // 2. if there is no opening '{' then a closing '{' is probably cruft.
438         if (!contains(data, '{'))
439                 data = strip(data, '}');
440         // happens, when last keyword
441         string::size_type const idx =
442                 !data.empty() ? data.find('=') : string::npos;
443
444         if (idx == string::npos)
445                 return string();
446
447         data = data.substr(idx);
448         data = frontStrip(strip(data));
449
450         if (data.length() < 2 || data[0] != '=') {      // a valid entry?
451                 return string();
452         } else {
453                 // delete '=' and the following spaces
454                 data = frontStrip(frontStrip(data,'='));
455                 if (data.length() < 2) {
456                         return data;    // not long enough to find delimiters
457                 } else {
458                         string::size_type keypos = 1;
459                         char enclosing;
460                         if (data[0] == '{') {
461                                 enclosing = '}';
462                         } else if (data[0] == '"') {
463                                 enclosing = '"';
464                         } else {
465                                 // no {} and no "", pure data but with a
466                                 // possible ',' at the end
467                                 return strip(data,',');
468                         }
469                         string tmp = data.substr(keypos);
470                         while (tmp.find('{') != string::npos &&
471                                tmp.find('}') != string::npos &&
472                                tmp.find('{') < tmp.find('}') &&
473                                tmp.find('{') < tmp.find(enclosing)) {
474
475                                 keypos += tmp.find('{') + 1;
476                                 tmp = data.substr(keypos);
477                                 keypos += tmp.find('}') + 1;
478                                 tmp = data.substr(keypos);
479                         }
480                         if (tmp.find(enclosing) == string::npos)
481                                 return data;
482                         else {
483                                 keypos += tmp.find(enclosing);
484                                 return data.substr(1, keypos - 1);
485                         }
486                 }
487         }
488 }
489
490
491 CitationStyle const getCitationStyle(string const & command)
492 {
493         if (command.empty()) return CitationStyle();
494
495         CitationStyle cs;
496         string cmd = command;
497
498         if (cmd[0] == 'C') {
499                 cs.forceUCase = true;
500                 cmd[0] = 'c';
501         }
502
503         size_t n = cmd.size()-1;
504         if (cmd[n] == '*') {
505                 cs.full = true;
506                 cmd = cmd.substr(0,n);
507         }
508
509         char const * const * const last = citeCommands + nCiteCommands;
510         char const * const * const ptr = std::find(citeCommands, last, cmd);
511
512         if (ptr != last) {
513                 size_t idx = ptr - citeCommands;
514                 cs.style = citeStyles[idx];
515         }
516
517         return cs;
518 }
519
520
521 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
522 {
523         string cite = citeCommands[command];
524         if (full) {
525                 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
526                 if (std::find(citeStylesFull, last, command) != last)
527                         cite += "*";
528         }
529
530         if (forceUCase) {
531                 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
532                 if (std::find(citeStylesUCase, last, command) != last)
533                         cite[0] = 'C';
534         }
535
536         return cite;
537 }
538
539
540 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
541 {
542         unsigned int nStyles = 1;
543         unsigned int start = 0;
544         if (usingNatbib) {
545                 nStyles = nCiteStyles - 1;
546                 start = 1;
547         }
548
549         vector<CiteStyle> styles(nStyles);
550
551         vector<CiteStyle>::size_type i = 0;
552         int j = start;
553         for (; i != styles.size(); ++i, ++j) {
554                 styles[i] = citeStyles[j];
555         }
556
557         return styles;
558 }
559
560
561 vector<string> const
562 getNumericalStrings(string const & key,
563                     InfoMap const & map, vector<CiteStyle> const & styles)
564 {
565         if (map.empty()) {
566                 return vector<string>();
567         }
568
569         string const author = getAbbreviatedAuthor(map, key);
570         string const year   = getYear(map, key);
571         if (author.empty() || year.empty())
572                 return vector<string>();
573
574         vector<string> vec(styles.size());
575         for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
576                 string str;
577
578                 switch (styles[i]) {
579                 case CITE:
580                 case CITEP:
581                         str = "[#ID]";
582                         break;
583
584                 case CITET:
585                         str = author + " [#ID]";
586                         break;
587
588                 case CITEALT:
589                         str = author + " #ID";
590                         break;
591
592                 case CITEALP:
593                         str = "#ID";
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
616 vector<string> const
617 getAuthorYearStrings(string const & key,
618                     InfoMap const & map, vector<CiteStyle> const & styles)
619 {
620         if (map.empty()) {
621                 return vector<string>();
622         }
623
624         string const author = getAbbreviatedAuthor(map, key);
625         string const year   = getYear(map, key);
626         if (author.empty() || year.empty())
627                 return vector<string>();
628
629         vector<string> vec(styles.size());
630         for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
631                 string str;
632
633                 switch (styles[i]) {
634                 case CITE:
635                 case CITET:
636                         str = author + " (" + year + ")";
637                         break;
638
639                 case CITEP:
640                         str = "(" + author + ", " + year + ")";
641                         break;
642
643                 case CITEALT:
644                         str = author + " " + year ;
645                         break;
646
647                 case CITEALP:
648                         str = author + ", " + year ;
649                         break;
650
651                 case CITEAUTHOR:
652                         str = author;
653                         break;
654
655                 case CITEYEAR:
656                         str = year;
657                         break;
658
659                 case CITEYEARPAR:
660                         str = "(" + year + ")";
661                         break;
662                 }
663
664                 vec[i] = str;
665         }
666
667         return vec;
668 }
669
670 } // namespace biblio