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 "gettext.h" // for _()
18 #include "helper_funcs.h"
19 #include "support/lstrings.h"
20 #include "support/LAssert.h"
22 #include <boost/regex.hpp>
23 #include "support/BoostFormat.h"
31 string const familyName(string const & name)
36 // possible authorname combinations are:
37 // "Surname, FirstName"
39 // "FirstName Surname"
41 string::size_type idx = fname.find(',');
42 if (idx != string::npos)
43 return ltrim(fname.substr(0, idx));
44 idx = fname.rfind('.');
45 if (idx != string::npos)
46 fname = ltrim(fname.substr(idx + 1));
47 // test if we have a LaTeX Space in front
49 return fname.substr(2);
55 string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
57 lyx::Assert(!map.empty());
59 InfoMap::const_iterator it = map.find(key);
62 string const & data = it->second;
64 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
65 string::size_type const pos = data.find("TheBibliographyRef");
66 if (pos != string::npos) {
71 string const opt = trim(data.substr(0, pos - 1));
76 split(opt, authors, '(');
80 string author = parseBibTeX(data, "author");
82 author = parseBibTeX(data, "editor");
85 author = parseBibTeX(data, "key");
91 vector<string> const authors = getVectorFromString(author, " and ");
96 boost::format fmter("");
97 if (authors.size() == 2)
98 fmter = boost::format(_("%1$s and %2$s"))
99 % familyName(authors[0]) % familyName(authors[1]);
100 else if (authors.size() > 2)
101 fmter = boost::format(_("%1$s et al.")) % familyName(authors[0]);
103 fmter = boost::format("%1$s") % familyName(authors[0]);
107 if (authors.size() == 2)
108 msg = familyName(authors[0]) + _(" and ") + familyName(authors[1]);
109 else if (authors.size() > 2)
110 msg = familyName(authors[0]) + _("et al.");
112 msg = familyName(authors[0]);
118 string const getYear(InfoMap const & map, string const & key)
120 lyx::Assert(!map.empty());
122 InfoMap::const_iterator it = map.find(key);
125 string const & data = it->second;
127 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
128 string::size_type const pos = data.find("TheBibliographyRef");
129 if (pos != string::npos) {
135 trim(data.substr(0, pos - 1));
140 string const tmp = split(opt, authors, '(');
142 split(tmp, year, ')');
147 string year = parseBibTeX(data, "year");
157 // A functor for use with std::sort, leading to case insensitive sorting
158 struct compareNoCase: public std::binary_function<string, string, bool>
160 bool operator()(string const & s1, string const & s2) const {
161 return compare_ascii_no_case(s1, s2) < 0;
168 vector<string> const getKeys(InfoMap const & map)
170 vector<string> bibkeys;
171 InfoMap::const_iterator it = map.begin();
172 InfoMap::const_iterator end = map.end();
173 for (; it != end; ++it) {
174 bibkeys.push_back(it->first);
177 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
182 string const getInfo(InfoMap const & map, string const & key)
184 lyx::Assert(!map.empty());
186 InfoMap::const_iterator it = map.find(key);
189 string const & data = it->second;
191 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
192 string const separator("TheBibliographyRef");
193 string::size_type const pos = data.find(separator);
194 if (pos != string::npos) {
195 string::size_type const pos2 = pos + separator.size();
196 string const info = trim(data.substr(pos2));
200 // Search for all possible "required" keys
201 string author = parseBibTeX(data, "author");
203 author = parseBibTeX(data, "editor");
205 string year = parseBibTeX(data, "year");
206 string title = parseBibTeX(data, "title");
207 string booktitle = parseBibTeX(data, "booktitle");
208 string chapter = parseBibTeX(data, "chapter");
209 string number = parseBibTeX(data, "number");
210 string volume = parseBibTeX(data, "volume");
211 string pages = parseBibTeX(data, "pages");
213 string media = parseBibTeX(data, "journal");
215 media = parseBibTeX(data, "publisher");
217 media = parseBibTeX(data, "school");
219 media = parseBibTeX(data, "institution");
221 ostringstream result;
223 result << author << ", ";
226 if (!booktitle.empty())
227 result << ", in " << booktitle;
228 if (!chapter.empty())
229 result << ", Ch. " << chapter;
231 result << ", " << media;
233 result << ", vol. " << volume;
235 result << ", no. " << number;
237 result << ", pp. " << pages;
239 result << ", " << year;
241 string const result_str = rtrim(STRCONV(result.str()));
242 if (!result_str.empty())
245 // This should never happen (or at least be very unusual!)
252 // Escape special chars.
253 // All characters are literals except: '.|*?+(){}[]^$\'
254 // These characters are literals when preceded by a "\", which is done here
255 string const escape_special_chars(string const & expr)
257 // Search for all chars '.|*?+(){}[^$]\'
258 // Note that '[' and '\' must be escaped.
259 // This is a limitation of boost::regex, but all other chars in BREs
260 // are assumed literal.
261 boost::RegEx reg("[].|*?+(){}^$\\[\\\\]");
263 // $& is a perl-like expression that expands to all of the current match
264 // The '$' must be prefixed with the escape character '\' for
265 // boost to treat it as a literal.
266 // Thus, to prefix a matched expression with '\', we use:
267 string const fmt("\\\\$&");
269 return reg.Merge(expr, fmt);
273 // A functor for use with std::find_if, used to ascertain whether a
274 // data entry matches the required regex_
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) {
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; }
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);
484 using namespace biblio;
486 char const * const citeCommands[] = {
487 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
488 "citeyear", "citeyearpar" };
490 unsigned int const nCiteCommands =
491 sizeof(citeCommands) / sizeof(char *);
493 CiteStyle const citeStyles[] = {
494 CITE, CITET, CITEP, CITEALT, CITEALP,
495 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
497 unsigned int const nCiteStyles =
498 sizeof(citeStyles) / sizeof(CiteStyle);
500 CiteStyle const citeStylesFull[] = {
501 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
503 unsigned int const nCiteStylesFull =
504 sizeof(citeStylesFull) / sizeof(CiteStyle);
506 CiteStyle const citeStylesUCase[] = {
507 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
509 unsigned int const nCiteStylesUCase =
510 sizeof(citeStylesUCase) / sizeof(CiteStyle);
515 CitationStyle const getCitationStyle(string const & command)
517 if (command.empty()) return CitationStyle();
520 string cmd = command;
523 cs.forceUCase = true;
527 size_t n = cmd.size() - 1;
530 cmd = cmd.substr(0,n);
533 char const * const * const last = citeCommands + nCiteCommands;
534 char const * const * const ptr = std::find(citeCommands, last, cmd);
537 size_t idx = ptr - citeCommands;
538 cs.style = citeStyles[idx];
545 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
547 string cite = citeCommands[command];
549 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
550 if (std::find(citeStylesFull, last, command) != last)
555 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
556 if (std::find(citeStylesUCase, last, command) != last)
564 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
566 unsigned int nStyles = 1;
567 unsigned int start = 0;
569 nStyles = nCiteStyles - 1;
573 vector<CiteStyle> styles(nStyles);
575 vector<CiteStyle>::size_type i = 0;
577 for (; i != styles.size(); ++i, ++j) {
578 styles[i] = citeStyles[j];
586 getNumericalStrings(string const & key,
587 InfoMap const & map, vector<CiteStyle> const & styles)
590 return vector<string>();
593 string const author = getAbbreviatedAuthor(map, key);
594 string const year = getYear(map, key);
595 if (author.empty() || year.empty())
596 return vector<string>();
598 vector<string> vec(styles.size());
599 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
609 str = author + " [#ID]";
613 str = author + " #ID";
629 str = '(' + year + ')';
641 getAuthorYearStrings(string const & key,
642 InfoMap const & map, vector<CiteStyle> const & styles)
645 return vector<string>();
648 string const author = getAbbreviatedAuthor(map, key);
649 string const year = getYear(map, key);
650 if (author.empty() || year.empty())
651 return vector<string>();
653 vector<string> vec(styles.size());
654 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
660 str = author + " (" + year + ')';
664 str = '(' + author + ", " + year + ')';
668 str = author + ' ' + year ;
672 str = author + ", " + year ;
684 str = '(' + year + ')';
694 } // namespace biblio