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;
38 using std::ostringstream;
44 string const familyName(string const & name)
49 // possible authorname combinations are:
50 // "Surname, FirstName"
52 // "FirstName Surname"
54 string::size_type idx = fname.find(',');
55 if (idx != string::npos)
56 return ltrim(fname.substr(0, idx));
57 idx = fname.rfind('.');
58 if (idx != string::npos)
59 fname = ltrim(fname.substr(idx + 1));
60 // test if we have a LaTeX Space in front
62 return fname.substr(2);
68 string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
70 BOOST_ASSERT(!map.empty());
72 InfoMap::const_iterator it = map.find(key);
75 string const & data = it->second;
77 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
78 string::size_type const pos = data.find("TheBibliographyRef");
79 if (pos != string::npos) {
84 string const opt = trim(data.substr(0, pos - 1));
89 split(opt, authors, '(');
93 string author = parseBibTeX(data, "author");
96 author = parseBibTeX(data, "editor");
99 author = parseBibTeX(data, "key");
105 vector<string> const authors = getVectorFromString(author, " and ");
109 if (authors.size() == 2)
110 return bformat(_("%1$s and %2$s"),
111 familyName(authors[0]), familyName(authors[1]));
113 if (authors.size() > 2)
114 return bformat(_("%1$s et al."), familyName(authors[0]));
116 return familyName(authors[0]);
120 string const getYear(InfoMap const & map, string const & key)
122 BOOST_ASSERT(!map.empty());
124 InfoMap::const_iterator it = map.find(key);
127 string const & data = it->second;
129 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
130 string::size_type const pos = data.find("TheBibliographyRef");
131 if (pos != string::npos) {
137 trim(data.substr(0, pos - 1));
142 string const tmp = split(opt, authors, '(');
144 split(tmp, year, ')');
149 string year = parseBibTeX(data, "year");
159 // A functor for use with std::sort, leading to case insensitive sorting
160 struct compareNoCase: public std::binary_function<string, string, bool>
162 bool operator()(string const & s1, string const & s2) const {
163 return compare_ascii_no_case(s1, s2) < 0;
170 vector<string> const getKeys(InfoMap const & map)
172 vector<string> bibkeys;
173 InfoMap::const_iterator it = map.begin();
174 InfoMap::const_iterator end = map.end();
175 for (; it != end; ++it) {
176 bibkeys.push_back(it->first);
179 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
184 string const getInfo(InfoMap const & map, string const & key)
186 BOOST_ASSERT(!map.empty());
188 InfoMap::const_iterator it = map.find(key);
191 string const & data = it->second;
193 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
194 string const separator("TheBibliographyRef");
195 string::size_type const pos = data.find(separator);
196 if (pos != string::npos) {
197 string::size_type const pos2 = pos + separator.size();
198 string const info = trim(data.substr(pos2));
202 // Search for all possible "required" keys
203 string author = parseBibTeX(data, "author");
205 author = parseBibTeX(data, "editor");
207 string year = parseBibTeX(data, "year");
208 string title = parseBibTeX(data, "title");
209 string booktitle = parseBibTeX(data, "booktitle");
210 string chapter = parseBibTeX(data, "chapter");
211 string number = parseBibTeX(data, "number");
212 string volume = parseBibTeX(data, "volume");
213 string pages = parseBibTeX(data, "pages");
215 string media = parseBibTeX(data, "journal");
217 media = parseBibTeX(data, "publisher");
219 media = parseBibTeX(data, "school");
221 media = parseBibTeX(data, "institution");
223 ostringstream result;
225 result << author << ", ";
228 if (!booktitle.empty())
229 result << ", in " << booktitle;
230 if (!chapter.empty())
231 result << ", Ch. " << chapter;
233 result << ", " << media;
235 result << ", vol. " << volume;
237 result << ", no. " << number;
239 result << ", pp. " << pages;
241 result << ", " << year;
243 string const result_str = rtrim(result.str());
244 if (!result_str.empty())
247 // This should never happen (or at least be very unusual!)
254 // Escape special chars.
255 // All characters are literals except: '.|*?+(){}[]^$\'
256 // These characters are literals when preceded by a "\", which is done here
257 string const escape_special_chars(string const & expr)
259 // Search for all chars '.|*?+(){}[^$]\'
260 // Note that '[' and '\' must be escaped.
261 // This is a limitation of boost::regex, but all other chars in BREs
262 // are assumed literal.
263 boost::RegEx reg("[].|*?+(){}^$\\[\\\\]");
265 // $& is a perl-like expression that expands to all of the current match
266 // The '$' must be prefixed with the escape character '\' for
267 // boost to treat it as a literal.
268 // Thus, to prefix a matched expression with '\', we use:
269 return reg.Merge(expr, "\\\\$&");
273 // A functor for use with std::find_if, used to ascertain whether a
274 // data entry matches the required regex_
275 struct RegexMatch : public std::unary_function<string, bool>
277 // re and icase are used to construct an instance of boost::RegEx.
278 // if icase is true, then matching is insensitive to case
279 RegexMatch(InfoMap const & m, string const & re, bool icase)
280 : map_(m), regex_(re, icase) {}
282 bool operator()(string const & key) const {
286 // the data searched is the key + its associated BibTeX/biblio
289 InfoMap::const_iterator info = map_.find(key);
290 if (info != map_.end())
291 data += ' ' + info->second;
293 // Attempts to find a match for the current RE
294 // somewhere in data.
295 return regex_.Search(data);
298 bool validRE() const { return regex_.error_code() == 0; }
302 mutable boost::RegEx regex_;
308 vector<string>::const_iterator
309 searchKeys(InfoMap const & theMap,
310 vector<string> const & keys,
311 string const & search_expr,
312 vector<string>::const_iterator start,
317 // Preliminary checks
318 if (start < keys.begin() || start >= keys.end())
321 string expr = trim(search_expr);
326 // We must escape special chars in the search_expr so that
327 // it is treated as a simple string by boost::regex.
328 expr = escape_special_chars(expr);
330 // Build the functor that will be passed to find_if.
331 RegexMatch const match(theMap, expr, !caseSensitive);
332 if (!match.validRE())
335 // Search the vector of 'keys' from 'start' for one that matches the
336 // predicate 'match'. Searching can be forward or backward from start.
338 return std::find_if(start, keys.end(), match);
340 vector<string>::const_reverse_iterator rit(start);
341 vector<string>::const_reverse_iterator rend = keys.rend();
342 rit = std::find_if(rit, rend, match);
346 // This is correct and always safe.
347 // (See Meyer's Effective STL, Item 28.)
348 return (++rit).base();
352 string const parseBibTeX(string data, string const & findkey)
355 // at first we delete all characters right of '%' and
356 // replace tabs through a space and remove leading spaces
357 // we read the data line by line so that the \n are
361 string dummy = token(data,'\n', Entries);
362 while (!dummy.empty()) {
363 dummy = subst(dummy, '\t', ' '); // no tabs
364 dummy = ltrim(dummy); // no leading spaces
365 // ignore lines with a beginning '%' or ignore all right of %
366 string::size_type const idx =
367 dummy.empty() ? string::npos : dummy.find('%');
368 if (idx != string::npos)
369 dummy.erase(idx, string::npos);
370 // do we have a new token or a new line of
371 // the same one? In the first case we ignore
372 // the \n and in the second we replace it
374 if (!dummy.empty()) {
375 if (!contains(dummy, "="))
376 data_ += ' ' + dummy;
380 dummy = token(data, '\n', ++Entries);
383 // replace double commas with "" for easy scanning
384 data = subst(data_, ",,", "\"\"");
390 // now get only the important line of the bibtex entry.
391 // all entries are devided by ',' except the last one.
392 data += ','; // now we have same behaviour for all entries
393 // because the last one is "blah ... }"
396 // parsing of title and booktitle is different from the
397 // others, because booktitle contains title
399 dummy = token(data, ',', Entries++);
400 if (!dummy.empty()) {
401 found = contains(ascii_lowercase(dummy), findkey);
402 if (findkey == "title" &&
403 contains(ascii_lowercase(dummy), "booktitle"))
406 } while (!found && !dummy.empty());
411 // we are not sure, if we get all, because "key= "blah, blah" is
413 // Therefore we read all until the next "=" character, which follows a
416 dummy = token(data, ',', Entries++);
417 while (!contains(dummy, '=') && !dummy.empty()) {
418 keyvalue += ',' + dummy;
419 dummy = token(data, ',', Entries++);
422 // replace double "" with originals ,, (two commas)
423 // leaving us with the all-important line
424 data = subst(keyvalue, "\"\"", ",,");
429 // 2. if there is no opening '{' then a closing '{' is probably cruft.
430 if (!contains(data, '{'))
431 data = rtrim(data, "}");
432 // happens, when last keyword
433 string::size_type const idx =
434 !data.empty() ? data.find('=') : string::npos;
436 if (idx == string::npos)
439 data = trim(data.substr(idx));
441 if (data.length() < 2 || data[0] != '=') { // a valid entry?
444 // delete '=' and the following spaces
445 data = ltrim(data, " =");
446 if (data.length() < 2) {
447 return data; // not long enough to find delimiters
449 string::size_type keypos = 1;
451 if (data[0] == '{') {
453 } else if (data[0] == '"') {
456 // no {} and no "", pure data but with a
457 // possible ',' at the end
458 return rtrim(data, ",");
460 string tmp = data.substr(keypos);
461 while (tmp.find('{') != string::npos &&
462 tmp.find('}') != string::npos &&
463 tmp.find('{') < tmp.find('}') &&
464 tmp.find('{') < tmp.find(enclosing)) {
466 keypos += tmp.find('{') + 1;
467 tmp = data.substr(keypos);
468 keypos += tmp.find('}') + 1;
469 tmp = data.substr(keypos);
471 if (tmp.find(enclosing) == string::npos)
474 keypos += tmp.find(enclosing);
475 return data.substr(1, keypos - 1);
485 char const * const citeCommands[] = {
486 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
487 "citeyear", "citeyearpar" };
489 unsigned int const nCiteCommands =
490 sizeof(citeCommands) / sizeof(char *);
492 CiteStyle const citeStyles[] = {
493 CITE, CITET, CITEP, CITEALT, CITEALP,
494 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
496 unsigned int const nCiteStyles =
497 sizeof(citeStyles) / sizeof(CiteStyle);
499 CiteStyle const citeStylesFull[] = {
500 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
502 unsigned int const nCiteStylesFull =
503 sizeof(citeStylesFull) / sizeof(CiteStyle);
505 CiteStyle const citeStylesUCase[] = {
506 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
508 unsigned int const nCiteStylesUCase =
509 sizeof(citeStylesUCase) / sizeof(CiteStyle);
514 CitationStyle const getCitationStyle(string const & command)
516 if (command.empty()) return CitationStyle();
519 string cmd = command;
522 cs.forceUCase = true;
526 size_t n = cmd.size() - 1;
529 cmd = cmd.substr(0,n);
532 char const * const * const last = citeCommands + nCiteCommands;
533 char const * const * const ptr = std::find(citeCommands, last, cmd);
536 size_t idx = ptr - citeCommands;
537 cs.style = citeStyles[idx];
544 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
546 string cite = citeCommands[command];
548 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
549 if (std::find(citeStylesFull, last, command) != last)
554 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
555 if (std::find(citeStylesUCase, last, command) != last)
563 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
565 unsigned int nStyles = 1;
566 unsigned int start = 0;
568 nStyles = nCiteStyles - 1;
572 vector<CiteStyle> styles(nStyles);
574 vector<CiteStyle>::size_type i = 0;
576 for (; i != styles.size(); ++i, ++j) {
577 styles[i] = citeStyles[j];
585 getNumericalStrings(string const & key,
586 InfoMap const & map, vector<CiteStyle> const & styles)
589 return vector<string>();
592 string const author = getAbbreviatedAuthor(map, key);
593 string const year = getYear(map, key);
594 if (author.empty() || year.empty())
595 return vector<string>();
597 vector<string> vec(styles.size());
598 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
608 str = author + " [#ID]";
612 str = author + " #ID";
628 str = '(' + year + ')';
640 getAuthorYearStrings(string const & key,
641 InfoMap const & map, vector<CiteStyle> const & styles)
644 return vector<string>();
647 string const author = getAbbreviatedAuthor(map, key);
648 string const year = getYear(map, key);
649 if (author.empty() || year.empty())
650 return vector<string>();
652 vector<string> vec(styles.size());
653 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
659 str = author + " (" + year + ')';
663 str = '(' + author + ", " + year + ')';
667 str = author + ' ' + year ;
671 str = author + ", " + year ;
683 str = '(' + year + ')';
693 } // namespace biblio