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.
17 #include "bufferparams.h"
20 #include "support/lstrings.h"
21 #include "support/std_sstream.h"
23 #include <boost/regex.hpp>
27 using lyx::support::ascii_lowercase;
28 using lyx::support::bformat;
29 using lyx::support::compare_ascii_no_case;
30 using lyx::support::contains;
31 using lyx::support::getVectorFromString;
32 using lyx::support::ltrim;
33 using lyx::support::rtrim;
34 using lyx::support::split;
35 using lyx::support::subst;
36 using lyx::support::token;
37 using lyx::support::trim;
40 using std::ostringstream;
46 string const familyName(string const & name)
51 // possible authorname combinations are:
52 // "Surname, FirstName"
54 // "FirstName Surname"
56 string::size_type idx = fname.find(',');
57 if (idx != string::npos)
58 return ltrim(fname.substr(0, idx));
59 idx = fname.rfind('.');
60 if (idx != string::npos)
61 fname = ltrim(fname.substr(idx + 1));
62 // test if we have a LaTeX Space in front
64 return fname.substr(2);
70 string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
72 BOOST_ASSERT(!map.empty());
74 InfoMap::const_iterator it = map.find(key);
77 string const & data = it->second;
79 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
80 string::size_type const pos = data.find("TheBibliographyRef");
81 if (pos != string::npos) {
86 string const opt = trim(data.substr(0, pos - 1));
91 split(opt, authors, '(');
95 string author = parseBibTeX(data, "author");
98 author = parseBibTeX(data, "editor");
100 if (author.empty()) {
101 author = parseBibTeX(data, "key");
107 vector<string> const authors = getVectorFromString(author, " and ");
111 if (authors.size() == 2)
112 return bformat(_("%1$s and %2$s"),
113 familyName(authors[0]), familyName(authors[1]));
115 if (authors.size() > 2)
116 return bformat(_("%1$s et al."), familyName(authors[0]));
118 return familyName(authors[0]);
122 string const getYear(InfoMap const & map, string const & key)
124 BOOST_ASSERT(!map.empty());
126 InfoMap::const_iterator it = map.find(key);
129 string const & data = it->second;
131 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
132 string::size_type const pos = data.find("TheBibliographyRef");
133 if (pos != string::npos) {
139 trim(data.substr(0, pos - 1));
144 string const tmp = split(opt, authors, '(');
146 split(tmp, year, ')');
151 string year = parseBibTeX(data, "year");
161 // A functor for use with std::sort, leading to case insensitive sorting
162 struct compareNoCase: public std::binary_function<string, string, bool>
164 bool operator()(string const & s1, string const & s2) const {
165 return compare_ascii_no_case(s1, s2) < 0;
172 vector<string> const getKeys(InfoMap const & map)
174 vector<string> bibkeys;
175 InfoMap::const_iterator it = map.begin();
176 InfoMap::const_iterator end = map.end();
177 for (; it != end; ++it) {
178 bibkeys.push_back(it->first);
181 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
186 string const getInfo(InfoMap const & map, string const & key)
188 BOOST_ASSERT(!map.empty());
190 InfoMap::const_iterator it = map.find(key);
193 string const & data = it->second;
195 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
196 string const separator("TheBibliographyRef");
197 string::size_type const pos = data.find(separator);
198 if (pos != string::npos) {
199 string::size_type const pos2 = pos + separator.size();
200 string const info = trim(data.substr(pos2));
204 // Search for all possible "required" keys
205 string author = parseBibTeX(data, "author");
207 author = parseBibTeX(data, "editor");
209 string year = parseBibTeX(data, "year");
210 string title = parseBibTeX(data, "title");
211 string booktitle = parseBibTeX(data, "booktitle");
212 string chapter = parseBibTeX(data, "chapter");
213 string number = parseBibTeX(data, "number");
214 string volume = parseBibTeX(data, "volume");
215 string pages = parseBibTeX(data, "pages");
217 string media = parseBibTeX(data, "journal");
219 media = parseBibTeX(data, "publisher");
221 media = parseBibTeX(data, "school");
223 media = parseBibTeX(data, "institution");
225 ostringstream result;
227 result << author << ", ";
230 if (!booktitle.empty())
231 result << ", in " << booktitle;
232 if (!chapter.empty())
233 result << ", Ch. " << chapter;
235 result << ", " << media;
237 result << ", vol. " << volume;
239 result << ", no. " << number;
241 result << ", pp. " << pages;
243 result << ", " << year;
245 string const result_str = rtrim(result.str());
246 if (!result_str.empty())
249 // This should never happen (or at least be very unusual!)
256 // Escape special chars.
257 // All characters are literals except: '.|*?+(){}[]^$\'
258 // These characters are literals when preceded by a "\", which is done here
259 string const escape_special_chars(string const & expr)
261 // Search for all chars '.|*?+(){}[^$]\'
262 // Note that '[' and '\' must be escaped.
263 // This is a limitation of boost::regex, but all other chars in BREs
264 // are assumed literal.
265 boost::RegEx reg("[].|*?+(){}^$\\[\\\\]");
267 // $& is a perl-like expression that expands to all of the current match
268 // The '$' must be prefixed with the escape character '\' for
269 // boost to treat it as a literal.
270 // Thus, to prefix a matched expression with '\', we use:
271 return reg.Merge(expr, "\\\\$&");
275 // A functor for use with std::find_if, used to ascertain whether a
276 // data entry matches the required regex_
277 struct RegexMatch : public std::unary_function<string, bool>
279 // re and icase are used to construct an instance of boost::RegEx.
280 // if icase is true, then matching is insensitive to case
281 RegexMatch(InfoMap const & m, string const & re, bool icase)
282 : map_(m), regex_(re, icase) {}
284 bool operator()(string const & key) const {
288 // the data searched is the key + its associated BibTeX/biblio
291 InfoMap::const_iterator info = map_.find(key);
292 if (info != map_.end())
293 data += ' ' + info->second;
295 // Attempts to find a match for the current RE
296 // somewhere in data.
297 return regex_.Search(data);
300 bool validRE() const { return regex_.error_code() == 0; }
304 mutable boost::RegEx regex_;
310 vector<string>::const_iterator
311 searchKeys(InfoMap const & theMap,
312 vector<string> const & keys,
313 string const & search_expr,
314 vector<string>::const_iterator start,
319 // Preliminary checks
320 if (start < keys.begin() || start >= keys.end())
323 string expr = trim(search_expr);
328 // We must escape special chars in the search_expr so that
329 // it is treated as a simple string by boost::regex.
330 expr = escape_special_chars(expr);
332 // Build the functor that will be passed to find_if.
333 RegexMatch const match(theMap, expr, !caseSensitive);
334 if (!match.validRE())
337 // Search the vector of 'keys' from 'start' for one that matches the
338 // predicate 'match'. Searching can be forward or backward from start.
340 return std::find_if(start, keys.end(), match);
342 vector<string>::const_reverse_iterator rit(start);
343 vector<string>::const_reverse_iterator rend = keys.rend();
344 rit = std::find_if(rit, rend, match);
348 // This is correct and always safe.
349 // (See Meyer's Effective STL, Item 28.)
350 return (++rit).base();
354 string const parseBibTeX(string data, string const & findkey)
357 // at first we delete all characters right of '%' and
358 // replace tabs through a space and remove leading spaces
359 // we read the data line by line so that the \n are
363 string dummy = token(data,'\n', Entries);
364 while (!dummy.empty()) {
365 dummy = subst(dummy, '\t', ' '); // no tabs
366 dummy = ltrim(dummy); // no leading spaces
367 // ignore lines with a beginning '%' or ignore all right of %
368 string::size_type const idx =
369 dummy.empty() ? string::npos : dummy.find('%');
370 if (idx != string::npos)
371 dummy.erase(idx, string::npos);
372 // do we have a new token or a new line of
373 // the same one? In the first case we ignore
374 // the \n and in the second we replace it
376 if (!dummy.empty()) {
377 if (!contains(dummy, '='))
378 data_ += ' ' + dummy;
382 dummy = token(data, '\n', ++Entries);
385 // replace double commas with "" for easy scanning
386 data = subst(data_, ",,", "\"\"");
392 // now get only the important line of the bibtex entry.
393 // all entries are devided by ',' except the last one.
394 data += ','; // now we have same behaviour for all entries
395 // because the last one is "blah ... }"
398 // parsing of title and booktitle is different from the
399 // others, because booktitle contains title
401 dummy = token(data, ',', Entries++);
402 if (!dummy.empty()) {
403 found = contains(ascii_lowercase(dummy), findkey);
404 if (findkey == "title" &&
405 contains(ascii_lowercase(dummy), "booktitle"))
408 } while (!found && !dummy.empty());
413 // we are not sure, if we get all, because "key= "blah, blah" is
415 // Therefore we read all until the next "=" character, which follows a
418 dummy = token(data, ',', Entries++);
419 while (!contains(dummy, '=') && !dummy.empty()) {
420 keyvalue += ',' + dummy;
421 dummy = token(data, ',', Entries++);
424 // replace double "" with originals ,, (two commas)
425 // leaving us with the all-important line
426 data = subst(keyvalue, "\"\"", ",,");
431 // 2. if there is no opening '{' then a closing '{' is probably cruft.
432 if (!contains(data, '{'))
433 data = rtrim(data, "}");
434 // happens, when last keyword
435 string::size_type const idx =
436 !data.empty() ? data.find('=') : string::npos;
438 if (idx == string::npos)
441 data = trim(data.substr(idx));
443 if (data.length() < 2 || data[0] != '=') { // a valid entry?
446 // delete '=' and the following spaces
447 data = ltrim(data, " =");
448 if (data.length() < 2) {
449 return data; // not long enough to find delimiters
451 string::size_type keypos = 1;
453 if (data[0] == '{') {
455 } else if (data[0] == '"') {
458 // no {} and no "", pure data but with a
459 // possible ',' at the end
460 return rtrim(data, ",");
462 string tmp = data.substr(keypos);
463 while (tmp.find('{') != string::npos &&
464 tmp.find('}') != string::npos &&
465 tmp.find('{') < tmp.find('}') &&
466 tmp.find('{') < tmp.find(enclosing)) {
468 keypos += tmp.find('{') + 1;
469 tmp = data.substr(keypos);
470 keypos += tmp.find('}') + 1;
471 tmp = data.substr(keypos);
473 if (tmp.find(enclosing) == string::npos)
476 keypos += tmp.find(enclosing);
477 return data.substr(1, keypos - 1);
487 char const * const citeCommands[] = {
488 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
489 "citeyear", "citeyearpar" };
491 unsigned int const nCiteCommands =
492 sizeof(citeCommands) / sizeof(char *);
494 CiteStyle const citeStyles[] = {
495 CITE, CITET, CITEP, CITEALT, CITEALP,
496 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
498 unsigned int const nCiteStyles =
499 sizeof(citeStyles) / sizeof(CiteStyle);
501 CiteStyle const citeStylesFull[] = {
502 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
504 unsigned int const nCiteStylesFull =
505 sizeof(citeStylesFull) / sizeof(CiteStyle);
507 CiteStyle const citeStylesUCase[] = {
508 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
510 unsigned int const nCiteStylesUCase =
511 sizeof(citeStylesUCase) / sizeof(CiteStyle);
516 CitationStyle const getCitationStyle(string const & command)
518 if (command.empty()) return CitationStyle();
521 string cmd = command;
524 cs.forceUCase = true;
528 size_t n = cmd.size() - 1;
531 cmd = cmd.substr(0,n);
534 char const * const * const last = citeCommands + nCiteCommands;
535 char const * const * const ptr = std::find(citeCommands, last, cmd);
538 size_t idx = ptr - citeCommands;
539 cs.style = citeStyles[idx];
546 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
548 string cite = citeCommands[command];
550 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
551 if (std::find(citeStylesFull, last, command) != last)
556 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
557 if (std::find(citeStylesUCase, last, command) != last)
565 CiteEngine getEngine(Buffer const & buffer)
567 CiteEngine engine = ENGINE_BASIC;
569 if (buffer.params().use_natbib) {
570 if (buffer.params().use_numerical_citations) {
571 engine = ENGINE_NATBIB_NUMERICAL;
573 engine = ENGINE_NATBIB_AUTHORYEAR;
577 if (buffer.params().use_jurabib)
578 engine = ENGINE_JURABIB;
584 vector<CiteStyle> const getCiteStyles(CiteEngine engine)
586 unsigned int nStyles = 0;
587 unsigned int start = 0;
594 case ENGINE_NATBIB_AUTHORYEAR:
595 case ENGINE_NATBIB_NUMERICAL:
596 nStyles = nCiteStyles - 1;
600 nStyles = nCiteStyles;
605 typedef vector<CiteStyle> cite_vec;
607 cite_vec styles(nStyles);
608 cite_vec::size_type i = 0;
610 for (; i != styles.size(); ++i, ++j)
611 styles[i] = citeStyles[j];
618 getNumericalStrings(string const & key,
619 InfoMap const & map, vector<CiteStyle> const & styles)
622 return vector<string>();
625 string const author = getAbbreviatedAuthor(map, key);
626 string const year = getYear(map, key);
627 if (author.empty() || year.empty())
628 return vector<string>();
630 vector<string> vec(styles.size());
631 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
641 str = author + " [#ID]";
645 str = author + " #ID";
661 str = '(' + year + ')';
673 getAuthorYearStrings(string const & key,
674 InfoMap const & map, vector<CiteStyle> const & styles)
677 return vector<string>();
680 string const author = getAbbreviatedAuthor(map, key);
681 string const year = getYear(map, key);
682 if (author.empty() || year.empty())
683 return vector<string>();
685 vector<string> vec(styles.size());
686 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
691 // jurabib only: Author/Annotator
692 // (i.e. the "before" field, 2nd opt arg)
693 str = author + "/<" + _("before") + '>';
697 str = author + " (" + year + ')';
701 str = '(' + author + ", " + year + ')';
705 str = author + ' ' + year ;
709 str = author + ", " + year ;
721 str = '(' + year + ')';
731 } // namespace biblio