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