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
15 #pragma implementation
20 #include "gettext.h" // for _()
21 #include "helper_funcs.h"
22 #include "support/lstrings.h"
23 #include "support/LAssert.h"
25 #include <boost/regex.hpp>
26 #include "BoostFormat.h"
34 string const familyName(string const & name)
39 // possible authorname combinations are:
40 // "Surname, FirstName"
42 // "FirstName 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
52 return fname.substr(2);
58 string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
60 lyx::Assert(!map.empty());
62 InfoMap::const_iterator it = map.find(key);
65 string const & data = it->second;
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) {
74 string const opt = trim(data.substr(0, pos - 1));
79 split(opt, authors, '(');
83 string author = parseBibTeX(data, "author");
85 author = parseBibTeX(data, "editor");
88 author = parseBibTeX(data, "key");
94 vector<string> const authors = getVectorFromString(author, " and ");
99 boost::format fmter("");
100 if (authors.size() == 2)
101 fmter = boost::format(_("%1$s and %2$s"))
102 % familyName(authors[0]) % familyName(authors[1]);
103 else if (authors.size() > 2)
104 fmter = boost::format(_("%1$s et al.")) % familyName(authors[0]);
106 fmter = boost::format("%1$s") % familyName(authors[0]);
110 if (authors.size() == 2)
111 msg = familyName(authors[0]) + _(" and ") + familyName(authors[1]);
112 else if (authors.size() > 2)
113 msg = familyName(authors[0]) + _("et al.");
115 msg = familyName(authors[0]);
121 string const getYear(InfoMap const & map, string const & key)
123 lyx::Assert(!map.empty());
125 InfoMap::const_iterator it = map.find(key);
128 string const & data = it->second;
130 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
131 string::size_type const pos = data.find("TheBibliographyRef");
132 if (pos != string::npos) {
138 trim(data.substr(0, pos - 1));
143 string const tmp = split(opt, authors, '(');
145 split(tmp, year, ')');
150 string year = parseBibTeX(data, "year");
160 // A functor for use with std::sort, leading to case insensitive sorting
161 struct compareNoCase: public std::binary_function<string, string, bool>
163 bool operator()(string const & s1, string const & s2) const {
164 return compare_ascii_no_case(s1, s2) < 0;
171 vector<string> const getKeys(InfoMap const & map)
173 vector<string> bibkeys;
174 InfoMap::const_iterator it = map.begin();
175 InfoMap::const_iterator end = map.end();
176 for (; it != end; ++it) {
177 bibkeys.push_back(it->first);
180 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
185 string const getInfo(InfoMap const & map, string const & key)
187 lyx::Assert(!map.empty());
189 InfoMap::const_iterator it = map.find(key);
192 string const & data = it->second;
194 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
195 string const separator("TheBibliographyRef");
196 string::size_type const pos = data.find(separator);
197 if (pos != string::npos) {
198 string::size_type const pos2 = pos + separator.size();
199 string const info = trim(data.substr(pos2));
203 // Search for all possible "required" keys
204 string author = parseBibTeX(data, "author");
206 author = parseBibTeX(data, "editor");
208 string year = parseBibTeX(data, "year");
209 string title = parseBibTeX(data, "title");
210 string booktitle = parseBibTeX(data, "booktitle");
211 string chapter = parseBibTeX(data, "chapter");
212 string number = parseBibTeX(data, "number");
213 string volume = parseBibTeX(data, "volume");
214 string pages = parseBibTeX(data, "pages");
216 string media = parseBibTeX(data, "journal");
218 media = parseBibTeX(data, "publisher");
220 media = parseBibTeX(data, "school");
222 media = parseBibTeX(data, "institution");
224 ostringstream result;
226 result << author << ", ";
229 if (!booktitle.empty())
230 result << ", in " << booktitle;
231 if (!chapter.empty())
232 result << ", Ch. " << chapter;
234 result << ", " << media;
236 result << ", vol. " << volume;
238 result << ", no. " << number;
240 result << ", pp. " << pages;
242 result << ", " << year;
244 string const result_str = rtrim(STRCONV(result.str()));
245 if (!result_str.empty())
248 // This should never happen (or at least be very unusual!)
255 // Escape special chars.
256 // All characters are literals except: '.|*?+(){}[]^$\'
257 // These characters are literals when preceded by a "\", which is done here
258 string const escape_special_chars(string const & expr)
260 // Search for all chars '.|*?+(){}[^$]\'
261 // Note that '[' and '\' must be escaped.
262 // This is a limitation of boost::regex, but all other chars in BREs
263 // are assumed literal.
264 boost::RegEx reg("[].|*?+(){}^$\\[\\\\]");
266 // $& is a perl-like expression that expands to all of the current match
267 // The '$' must be prefixed with the escape character '\' for
268 // boost to treat it as a literal.
269 // Thus, to prefix a matched expression with '\', we use:
270 string const fmt("\\\\$&");
272 return reg.Merge(expr, fmt);
276 // A functor for use with std::find_if, used to ascertain whether a
277 // data entry matches the required regex_
280 // re and icase are used to construct an instance of boost::RegEx.
281 // if icase is true, then matching is insensitive to case
282 RegexMatch(InfoMap const & m, string const & re, bool icase)
283 : map_(m), regex_(re, icase) {}
285 bool operator()(string const & key) {
289 // the data searched is the key + its associated BibTeX/biblio
292 InfoMap::const_iterator info = map_.find(key);
293 if (info != map_.end())
294 data += " " + info->second;
296 // Attempts to find a match for the current RE
297 // somewhere in data.
298 return regex_.Search(data);
301 bool validRE() const { return regex_.error_code() == 0; }
311 vector<string>::const_iterator
312 searchKeys(InfoMap const & theMap,
313 vector<string> const & keys,
314 string const & search_expr,
315 vector<string>::const_iterator start,
320 // Preliminary checks
321 if (start < keys.begin() || start >= keys.end())
324 string expr = trim(search_expr);
329 // We must escape special chars in the search_expr so that
330 // it is treated as a simple string by boost::regex.
331 expr = escape_special_chars(expr);
333 // Build the functor that will be passed to find_if.
334 RegexMatch const match(theMap, expr, !caseSensitive);
335 if (!match.validRE())
338 // Search the vector of 'keys' from 'start' for one that matches the
339 // predicate 'match'. Searching can be forward or backward from start.
341 return std::find_if(start, keys.end(), match);
343 vector<string>::const_reverse_iterator rit(start);
344 vector<string>::const_reverse_iterator rend = keys.rend();
345 rit = std::find_if(rit, rend, match);
349 // This is correct and always safe.
350 // (See Meyer's Effective STL, Item 28.)
351 return (++rit).base();
355 string const parseBibTeX(string data, string const & findkey)
358 // at first we delete all characters right of '%' and
359 // replace tabs through a space and remove leading spaces
360 // we read the data line by line so that the \n are
364 string dummy = token(data,'\n', Entries);
365 while (!dummy.empty()) {
366 dummy = subst(dummy, '\t', ' '); // no tabs
367 dummy = ltrim(dummy); // no leading spaces
368 // ignore lines with a beginning '%' or ignore all right of %
369 string::size_type const idx =
370 dummy.empty() ? string::npos : dummy.find('%');
371 if (idx != string::npos)
372 dummy.erase(idx, string::npos);
373 // do we have a new token or a new line of
374 // the same one? In the first case we ignore
375 // the \n and in the second we replace it
377 if (!dummy.empty()) {
378 if (!contains(dummy, "="))
379 data_ += (' ' + dummy);
383 dummy = token(data, '\n', ++Entries);
386 // replace double commas with "" for easy scanning
387 data = subst(data_, ",,", "\"\"");
393 // now get only the important line of the bibtex entry.
394 // all entries are devided by ',' except the last one.
395 data += ','; // now we have same behaviour for all entries
396 // because the last one is "blah ... }"
399 // parsing of title and booktitle is different from the
400 // others, because booktitle contains title
402 dummy = token(data, ',', Entries++);
403 if (!dummy.empty()) {
404 found = contains(ascii_lowercase(dummy), findkey);
405 if (findkey == "title" &&
406 contains(ascii_lowercase(dummy), "booktitle"))
409 } while (!found && !dummy.empty());
414 // we are not sure, if we get all, because "key= "blah, blah" is
416 // Therefore we read all until the next "=" character, which follows a
419 dummy = token(data, ',', Entries++);
420 while (!contains(dummy, '=') && !dummy.empty()) {
421 keyvalue += (',' + dummy);
422 dummy = token(data, ',', Entries++);
425 // replace double "" with originals ,, (two commas)
426 // leaving us with the all-important line
427 data = subst(keyvalue, "\"\"", ",,");
432 // 2. if there is no opening '{' then a closing '{' is probably cruft.
433 if (!contains(data, '{'))
434 data = rtrim(data, "}");
435 // happens, when last keyword
436 string::size_type const idx =
437 !data.empty() ? data.find('=') : string::npos;
439 if (idx == string::npos)
442 data = trim(data.substr(idx));
444 if (data.length() < 2 || data[0] != '=') { // a valid entry?
447 // delete '=' and the following spaces
448 data = ltrim(data, " =");
449 if (data.length() < 2) {
450 return data; // not long enough to find delimiters
452 string::size_type keypos = 1;
454 if (data[0] == '{') {
456 } else if (data[0] == '"') {
459 // no {} and no "", pure data but with a
460 // possible ',' at the end
461 return rtrim(data, ",");
463 string tmp = data.substr(keypos);
464 while (tmp.find('{') != string::npos &&
465 tmp.find('}') != string::npos &&
466 tmp.find('{') < tmp.find('}') &&
467 tmp.find('{') < tmp.find(enclosing)) {
469 keypos += tmp.find('{') + 1;
470 tmp = data.substr(keypos);
471 keypos += tmp.find('}') + 1;
472 tmp = data.substr(keypos);
474 if (tmp.find(enclosing) == string::npos)
477 keypos += tmp.find(enclosing);
478 return data.substr(1, keypos - 1);
487 using namespace biblio;
489 char const * const citeCommands[] = {
490 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
491 "citeyear", "citeyearpar" };
493 unsigned int const nCiteCommands =
494 sizeof(citeCommands) / sizeof(char *);
496 CiteStyle const citeStyles[] = {
497 CITE, CITET, CITEP, CITEALT, CITEALP,
498 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
500 unsigned int const nCiteStyles =
501 sizeof(citeStyles) / sizeof(CiteStyle);
503 CiteStyle const citeStylesFull[] = {
504 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
506 unsigned int const nCiteStylesFull =
507 sizeof(citeStylesFull) / sizeof(CiteStyle);
509 CiteStyle const citeStylesUCase[] = {
510 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
512 unsigned int const nCiteStylesUCase =
513 sizeof(citeStylesUCase) / sizeof(CiteStyle);
518 CitationStyle const getCitationStyle(string const & command)
520 if (command.empty()) return CitationStyle();
523 string cmd = command;
526 cs.forceUCase = true;
530 size_t n = cmd.size() - 1;
533 cmd = cmd.substr(0,n);
536 char const * const * const last = citeCommands + nCiteCommands;
537 char const * const * const ptr = std::find(citeCommands, last, cmd);
540 size_t idx = ptr - citeCommands;
541 cs.style = citeStyles[idx];
548 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
550 string cite = citeCommands[command];
552 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
553 if (std::find(citeStylesFull, last, command) != last)
558 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
559 if (std::find(citeStylesUCase, last, command) != last)
567 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
569 unsigned int nStyles = 1;
570 unsigned int start = 0;
572 nStyles = nCiteStyles - 1;
576 vector<CiteStyle> styles(nStyles);
578 vector<CiteStyle>::size_type i = 0;
580 for (; i != styles.size(); ++i, ++j) {
581 styles[i] = citeStyles[j];
589 getNumericalStrings(string const & key,
590 InfoMap const & map, vector<CiteStyle> const & styles)
593 return vector<string>();
596 string const author = getAbbreviatedAuthor(map, key);
597 string const year = getYear(map, key);
598 if (author.empty() || year.empty())
599 return vector<string>();
601 vector<string> vec(styles.size());
602 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
612 str = author + " [#ID]";
616 str = author + " #ID";
632 str = "(" + year + ")";
644 getAuthorYearStrings(string const & key,
645 InfoMap const & map, vector<CiteStyle> const & styles)
648 return vector<string>();
651 string const author = getAbbreviatedAuthor(map, key);
652 string const year = getYear(map, key);
653 if (author.empty() || year.empty())
654 return vector<string>();
656 vector<string> vec(styles.size());
657 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
663 str = author + " (" + year + ")";
667 str = "(" + author + ", " + year + ")";
671 str = author + " " + year ;
675 str = author + ", " + year ;
687 str = "(" + year + ")";
697 } // namespace biblio