3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
9 * Full author contact details are available in file CREDITS.
16 #include "support/std_sstream.h"
17 #include "gettext.h" // for _()
19 #include "support/lstrings.h"
21 #include <boost/regex.hpp>
25 using lyx::support::ascii_lowercase;
26 using lyx::support::bformat;
27 using lyx::support::compare_ascii_no_case;
28 using lyx::support::contains;
29 using lyx::support::getVectorFromString;
30 using lyx::support::ltrim;
31 using lyx::support::rtrim;
32 using lyx::support::split;
33 using lyx::support::subst;
34 using lyx::support::token;
35 using lyx::support::trim;
37 using std::ostringstream;
43 string const familyName(string const & name)
48 // possible authorname combinations are:
49 // "Surname, FirstName"
51 // "FirstName Surname"
53 string::size_type idx = fname.find(',');
54 if (idx != string::npos)
55 return ltrim(fname.substr(0, idx));
56 idx = fname.rfind('.');
57 if (idx != string::npos)
58 fname = ltrim(fname.substr(idx + 1));
59 // test if we have a LaTeX Space in front
61 return fname.substr(2);
67 string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
69 BOOST_ASSERT(!map.empty());
71 InfoMap::const_iterator it = map.find(key);
74 string const & data = it->second;
76 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
77 string::size_type const pos = data.find("TheBibliographyRef");
78 if (pos != string::npos) {
83 string const opt = trim(data.substr(0, pos - 1));
88 split(opt, authors, '(');
92 string author = parseBibTeX(data, "author");
95 author = parseBibTeX(data, "editor");
98 author = parseBibTeX(data, "key");
104 vector<string> const authors = getVectorFromString(author, " and ");
108 if (authors.size() == 2)
109 return bformat(_("%1$s and %2$s"),
110 familyName(authors[0]), familyName(authors[1]));
112 if (authors.size() > 2)
113 return bformat(_("%1$s et al."), familyName(authors[0]));
115 return familyName(authors[0]);
119 string const getYear(InfoMap const & map, string const & key)
121 BOOST_ASSERT(!map.empty());
123 InfoMap::const_iterator it = map.find(key);
126 string const & data = it->second;
128 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
129 string::size_type const pos = data.find("TheBibliographyRef");
130 if (pos != string::npos) {
136 trim(data.substr(0, pos - 1));
141 string const tmp = split(opt, authors, '(');
143 split(tmp, year, ')');
148 string year = parseBibTeX(data, "year");
158 // A functor for use with std::sort, leading to case insensitive sorting
159 struct compareNoCase: public std::binary_function<string, string, bool>
161 bool operator()(string const & s1, string const & s2) const {
162 return compare_ascii_no_case(s1, s2) < 0;
169 vector<string> const getKeys(InfoMap const & map)
171 vector<string> bibkeys;
172 InfoMap::const_iterator it = map.begin();
173 InfoMap::const_iterator end = map.end();
174 for (; it != end; ++it) {
175 bibkeys.push_back(it->first);
178 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
183 string const getInfo(InfoMap const & map, string const & key)
185 BOOST_ASSERT(!map.empty());
187 InfoMap::const_iterator it = map.find(key);
190 string const & data = it->second;
192 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
193 string const separator("TheBibliographyRef");
194 string::size_type const pos = data.find(separator);
195 if (pos != string::npos) {
196 string::size_type const pos2 = pos + separator.size();
197 string const info = trim(data.substr(pos2));
201 // Search for all possible "required" keys
202 string author = parseBibTeX(data, "author");
204 author = parseBibTeX(data, "editor");
206 string year = parseBibTeX(data, "year");
207 string title = parseBibTeX(data, "title");
208 string booktitle = parseBibTeX(data, "booktitle");
209 string chapter = parseBibTeX(data, "chapter");
210 string number = parseBibTeX(data, "number");
211 string volume = parseBibTeX(data, "volume");
212 string pages = parseBibTeX(data, "pages");
214 string media = parseBibTeX(data, "journal");
216 media = parseBibTeX(data, "publisher");
218 media = parseBibTeX(data, "school");
220 media = parseBibTeX(data, "institution");
222 ostringstream result;
224 result << author << ", ";
227 if (!booktitle.empty())
228 result << ", in " << booktitle;
229 if (!chapter.empty())
230 result << ", Ch. " << chapter;
232 result << ", " << media;
234 result << ", vol. " << volume;
236 result << ", no. " << number;
238 result << ", pp. " << pages;
240 result << ", " << year;
242 string const result_str = rtrim(result.str());
243 if (!result_str.empty())
246 // This should never happen (or at least be very unusual!)
253 // Escape special chars.
254 // All characters are literals except: '.|*?+(){}[]^$\'
255 // These characters are literals when preceded by a "\", which is done here
256 string const escape_special_chars(string const & expr)
258 // Search for all chars '.|*?+(){}[^$]\'
259 // Note that '[' and '\' must be escaped.
260 // This is a limitation of boost::regex, but all other chars in BREs
261 // are assumed literal.
262 boost::RegEx reg("[].|*?+(){}^$\\[\\\\]");
264 // $& is a perl-like expression that expands to all of the current match
265 // The '$' must be prefixed with the escape character '\' for
266 // boost to treat it as a literal.
267 // Thus, to prefix a matched expression with '\', we use:
268 return reg.Merge(expr, "\\\\$&");
272 // A functor for use with std::find_if, used to ascertain whether a
273 // data entry matches the required regex_
276 // re and icase are used to construct an instance of boost::RegEx.
277 // if icase is true, then matching is insensitive to case
278 RegexMatch(InfoMap const & m, string const & re, bool icase)
279 : map_(m), regex_(re, icase) {}
281 bool operator()(string const & key) {
285 // the data searched is the key + its associated BibTeX/biblio
288 InfoMap::const_iterator info = map_.find(key);
289 if (info != map_.end())
290 data += ' ' + info->second;
292 // Attempts to find a match for the current RE
293 // somewhere in data.
294 return regex_.Search(data);
297 bool validRE() const { return regex_.error_code() == 0; }
307 vector<string>::const_iterator
308 searchKeys(InfoMap const & theMap,
309 vector<string> const & keys,
310 string const & search_expr,
311 vector<string>::const_iterator start,
316 // Preliminary checks
317 if (start < keys.begin() || start >= keys.end())
320 string expr = trim(search_expr);
325 // We must escape special chars in the search_expr so that
326 // it is treated as a simple string by boost::regex.
327 expr = escape_special_chars(expr);
329 // Build the functor that will be passed to find_if.
330 RegexMatch const match(theMap, expr, !caseSensitive);
331 if (!match.validRE())
334 // Search the vector of 'keys' from 'start' for one that matches the
335 // predicate 'match'. Searching can be forward or backward from start.
337 return std::find_if(start, keys.end(), match);
339 vector<string>::const_reverse_iterator rit(start);
340 vector<string>::const_reverse_iterator rend = keys.rend();
341 rit = std::find_if(rit, rend, match);
345 // This is correct and always safe.
346 // (See Meyer's Effective STL, Item 28.)
347 return (++rit).base();
351 string const parseBibTeX(string data, string const & findkey)
354 // at first we delete all characters right of '%' and
355 // replace tabs through a space and remove leading spaces
356 // we read the data line by line so that the \n are
360 string dummy = token(data,'\n', Entries);
361 while (!dummy.empty()) {
362 dummy = subst(dummy, '\t', ' '); // no tabs
363 dummy = ltrim(dummy); // no leading spaces
364 // ignore lines with a beginning '%' or ignore all right of %
365 string::size_type const idx =
366 dummy.empty() ? string::npos : dummy.find('%');
367 if (idx != string::npos)
368 dummy.erase(idx, string::npos);
369 // do we have a new token or a new line of
370 // the same one? In the first case we ignore
371 // the \n and in the second we replace it
373 if (!dummy.empty()) {
374 if (!contains(dummy, "="))
375 data_ += ' ' + dummy;
379 dummy = token(data, '\n', ++Entries);
382 // replace double commas with "" for easy scanning
383 data = subst(data_, ",,", "\"\"");
389 // now get only the important line of the bibtex entry.
390 // all entries are devided by ',' except the last one.
391 data += ','; // now we have same behaviour for all entries
392 // because the last one is "blah ... }"
395 // parsing of title and booktitle is different from the
396 // others, because booktitle contains title
398 dummy = token(data, ',', Entries++);
399 if (!dummy.empty()) {
400 found = contains(ascii_lowercase(dummy), findkey);
401 if (findkey == "title" &&
402 contains(ascii_lowercase(dummy), "booktitle"))
405 } while (!found && !dummy.empty());
410 // we are not sure, if we get all, because "key= "blah, blah" is
412 // Therefore we read all until the next "=" character, which follows a
415 dummy = token(data, ',', Entries++);
416 while (!contains(dummy, '=') && !dummy.empty()) {
417 keyvalue += ',' + dummy;
418 dummy = token(data, ',', Entries++);
421 // replace double "" with originals ,, (two commas)
422 // leaving us with the all-important line
423 data = subst(keyvalue, "\"\"", ",,");
428 // 2. if there is no opening '{' then a closing '{' is probably cruft.
429 if (!contains(data, '{'))
430 data = rtrim(data, "}");
431 // happens, when last keyword
432 string::size_type const idx =
433 !data.empty() ? data.find('=') : string::npos;
435 if (idx == string::npos)
438 data = trim(data.substr(idx));
440 if (data.length() < 2 || data[0] != '=') { // a valid entry?
443 // delete '=' and the following spaces
444 data = ltrim(data, " =");
445 if (data.length() < 2) {
446 return data; // not long enough to find delimiters
448 string::size_type keypos = 1;
450 if (data[0] == '{') {
452 } else if (data[0] == '"') {
455 // no {} and no "", pure data but with a
456 // possible ',' at the end
457 return rtrim(data, ",");
459 string tmp = data.substr(keypos);
460 while (tmp.find('{') != string::npos &&
461 tmp.find('}') != string::npos &&
462 tmp.find('{') < tmp.find('}') &&
463 tmp.find('{') < tmp.find(enclosing)) {
465 keypos += tmp.find('{') + 1;
466 tmp = data.substr(keypos);
467 keypos += tmp.find('}') + 1;
468 tmp = data.substr(keypos);
470 if (tmp.find(enclosing) == string::npos)
473 keypos += tmp.find(enclosing);
474 return data.substr(1, keypos - 1);
484 char const * const citeCommands[] = {
485 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
486 "citeyear", "citeyearpar" };
488 unsigned int const nCiteCommands =
489 sizeof(citeCommands) / sizeof(char *);
491 CiteStyle const citeStyles[] = {
492 CITE, CITET, CITEP, CITEALT, CITEALP,
493 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
495 unsigned int const nCiteStyles =
496 sizeof(citeStyles) / sizeof(CiteStyle);
498 CiteStyle const citeStylesFull[] = {
499 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
501 unsigned int const nCiteStylesFull =
502 sizeof(citeStylesFull) / sizeof(CiteStyle);
504 CiteStyle const citeStylesUCase[] = {
505 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
507 unsigned int const nCiteStylesUCase =
508 sizeof(citeStylesUCase) / sizeof(CiteStyle);
513 CitationStyle const getCitationStyle(string const & command)
515 if (command.empty()) return CitationStyle();
518 string cmd = command;
521 cs.forceUCase = true;
525 size_t n = cmd.size() - 1;
528 cmd = cmd.substr(0,n);
531 char const * const * const last = citeCommands + nCiteCommands;
532 char const * const * const ptr = std::find(citeCommands, last, cmd);
535 size_t idx = ptr - citeCommands;
536 cs.style = citeStyles[idx];
543 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
545 string cite = citeCommands[command];
547 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
548 if (std::find(citeStylesFull, last, command) != last)
553 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
554 if (std::find(citeStylesUCase, last, command) != last)
562 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
564 unsigned int nStyles = 1;
565 unsigned int start = 0;
567 nStyles = nCiteStyles - 1;
571 vector<CiteStyle> styles(nStyles);
573 vector<CiteStyle>::size_type i = 0;
575 for (; i != styles.size(); ++i, ++j) {
576 styles[i] = citeStyles[j];
584 getNumericalStrings(string const & key,
585 InfoMap const & map, vector<CiteStyle> const & styles)
588 return vector<string>();
591 string const author = getAbbreviatedAuthor(map, key);
592 string const year = getYear(map, key);
593 if (author.empty() || year.empty())
594 return vector<string>();
596 vector<string> vec(styles.size());
597 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
607 str = author + " [#ID]";
611 str = author + " #ID";
627 str = '(' + year + ')';
639 getAuthorYearStrings(string const & key,
640 InfoMap const & map, vector<CiteStyle> const & styles)
643 return vector<string>();
646 string const author = getAbbreviatedAuthor(map, key);
647 string const year = getYear(map, key);
648 if (author.empty() || year.empty())
649 return vector<string>();
651 vector<string> vec(styles.size());
652 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
658 str = author + " (" + year + ')';
662 str = '(' + author + ", " + year + ')';
666 str = author + ' ' + year ;
670 str = author + ", " + year ;
682 str = '(' + year + ')';
692 } // namespace biblio