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>
33 string const familyName(string const & name)
38 // possible authorname combinations are:
39 // "Surname, FirstName"
41 // "FirstName Surname"
43 string::size_type idx = fname.find(",");
44 if (idx != string::npos)
45 return ltrim(fname.substr(0, idx));
46 idx = fname.rfind(".");
47 if (idx != string::npos)
48 fname = ltrim(fname.substr(idx + 1));
49 // test if we have a LaTeX Space in front
51 return fname.substr(2);
57 string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
59 lyx::Assert(!map.empty());
61 InfoMap::const_iterator it = map.find(key);
64 string const & data = it->second;
66 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
67 string::size_type const pos = data.find("TheBibliographyRef");
68 if (pos != string::npos) {
73 string const opt = trim(data.substr(0, pos - 1));
78 split(opt, authors, '(');
82 string author = parseBibTeX(data, "author");
84 author = parseBibTeX(data, "editor");
87 author = parseBibTeX(data, "key");
93 vector<string> const authors = getVectorFromString(author, " and ");
97 author = familyName(authors[0]);
98 if (authors.size() == 2)
99 author += _(" and ") + familyName(authors[1]);
100 else if (authors.size() > 2)
101 author += _(" et al.");
107 string const getYear(InfoMap const & map, string const & key)
109 lyx::Assert(!map.empty());
111 InfoMap::const_iterator it = map.find(key);
114 string const & data = it->second;
116 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
117 string::size_type const pos = data.find("TheBibliographyRef");
118 if (pos != string::npos) {
124 trim(data.substr(0, pos - 1));
129 string const tmp = split(opt, authors, '(');
131 split(tmp, year, ')');
136 string year = parseBibTeX(data, "year");
146 // A functor for use with std::sort, leading to case insensitive sorting
147 struct compareNoCase: public std::binary_function<string, string, bool>
149 bool operator()(string const & s1, string const & s2) const {
150 return compare_ascii_no_case(s1, s2) < 0;
157 vector<string> const getKeys(InfoMap const & map)
159 vector<string> bibkeys;
160 InfoMap::const_iterator it = map.begin();
161 InfoMap::const_iterator end = map.end();
162 for (; it != end; ++it) {
163 bibkeys.push_back(it->first);
166 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
171 string const getInfo(InfoMap const & map, string const & key)
173 lyx::Assert(!map.empty());
175 InfoMap::const_iterator it = map.find(key);
178 string const & data = it->second;
180 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
181 string const separator("TheBibliographyRef");
182 string::size_type const pos = data.find(separator);
183 if (pos != string::npos) {
184 string::size_type const pos2 = pos + separator.size();
185 string const info = trim(data.substr(pos2));
189 // Search for all possible "required" keys
190 string author = parseBibTeX(data, "author");
192 author = parseBibTeX(data, "editor");
194 string year = parseBibTeX(data, "year");
195 string title = parseBibTeX(data, "title");
196 string booktitle = parseBibTeX(data, "booktitle");
197 string chapter = parseBibTeX(data, "chapter");
198 string number = parseBibTeX(data, "number");
199 string volume = parseBibTeX(data, "volume");
200 string pages = parseBibTeX(data, "pages");
202 string media = parseBibTeX(data, "journal");
204 media = parseBibTeX(data, "publisher");
206 media = parseBibTeX(data, "school");
208 media = parseBibTeX(data, "institution");
210 ostringstream result;
212 result << author << ", ";
215 if (!booktitle.empty())
216 result << ", in " << booktitle;
217 if (!chapter.empty())
218 result << ", Ch. " << chapter;
220 result << ", " << media;
222 result << ", vol. " << volume;
224 result << ", no. " << number;
226 result << ", pp. " << pages;
228 result << ", " << year;
230 string const result_str = rtrim(STRCONV(result.str()));
231 if (!result_str.empty())
234 // This should never happen (or at least be very unusual!)
241 // Escape special chars.
242 // All characters are literals except: '.|*?+(){}[]^$\'
243 // These characters are literals when preceded by a "\", which is done here
244 string const escape_special_chars(string const & expr)
246 // Search for all chars '.|*?+(){}[^$]\'
247 // Note that '[', ']' and '\' must be escaped.
248 // This is a limitation of boost::regex, but all other chars in BREs
249 // are assumed literal.
250 boost::RegEx reg("[.|*?+(){}^$\\[\\]\\\\]");
252 // $& is a perl-like expression that expands to all of the current match
253 // The '$' must be prefixed with the escape character '\' for
254 // boost to treat it as a literal.
255 // Thus, to prefix a matched expression with '\', we use:
256 string const fmt("\\\\$&");
258 return reg.Merge(expr, fmt);
262 // A functor for use with std::find_if, used to ascertain whether a
263 // data entry matches the required regex_
266 // re and icase are used to construct an instance of boost::RegEx.
267 // if icase is true, then matching is insensitive to case
268 RegexMatch(InfoMap const & m, string const & re, bool icase)
269 : map_(m), regex_(re, icase) {}
271 bool operator()(string const & key) {
275 // the data searched is the key + its associated BibTeX/biblio
278 InfoMap::const_iterator info = map_.find(key);
279 if (info != map_.end())
280 data += " " + info->second;
282 // Attempts to find a match for the current RE
283 // somewhere in data.
284 return regex_.Search(data);
287 bool validRE() const { return regex_.error_code() == 0; }
297 vector<string>::const_iterator
298 searchKeys(InfoMap const & theMap,
299 vector<string> const & keys,
300 string const & search_expr,
301 vector<string>::const_iterator start,
306 // Preliminary checks
307 if (start < keys.begin() || start >= keys.end())
310 string expr = trim(search_expr);
315 // We must escape special chars in the search_expr so that
316 // it is treated as a simple string by boost::regex.
317 expr = escape_special_chars(expr);
319 // Build the functor that will be passed to find_if.
320 RegexMatch const match(theMap, expr, !caseSensitive);
321 if (!match.validRE())
324 // Search the vector of 'keys' from 'start' for one that matches the
325 // predicate 'match'. Searching can be forward or backward from start.
327 return std::find_if(start, keys.end(), match);
329 vector<string>::const_reverse_iterator rit(start);
330 vector<string>::const_reverse_iterator rend = keys.rend();
331 rit = std::find_if(rit, rend, match);
335 // This is correct and always safe.
336 // (See Meyer's Effective STL, Item 28.)
337 return (++rit).base();
341 string const parseBibTeX(string data, string const & findkey)
344 // at first we delete all characters right of '%' and
345 // replace tabs through a space and remove leading spaces
346 // we read the data line by line so that the \n are
350 string dummy = token(data,'\n', Entries);
351 while (!dummy.empty()) {
352 dummy = subst(dummy, '\t', ' '); // no tabs
353 dummy = ltrim(dummy); // no leading spaces
354 // ignore lines with a beginning '%' or ignore all right of %
355 string::size_type const idx =
356 dummy.empty() ? string::npos : dummy.find('%');
357 if (idx != string::npos)
358 dummy.erase(idx, string::npos);
359 // do we have a new token or a new line of
360 // the same one? In the first case we ignore
361 // the \n and in the second we replace it
363 if (!dummy.empty()) {
364 if (!contains(dummy, "="))
365 data_ += (' ' + dummy);
369 dummy = token(data, '\n', ++Entries);
372 // replace double commas with "" for easy scanning
373 data = subst(data_, ",,", "\"\"");
379 // now get only the important line of the bibtex entry.
380 // all entries are devided by ',' except the last one.
381 data += ','; // now we have same behaviour for all entries
382 // because the last one is "blah ... }"
385 // parsing of title and booktitle is different from the
386 // others, because booktitle contains title
388 dummy = token(data, ',', Entries++);
389 if (!dummy.empty()) {
390 found = contains(ascii_lowercase(dummy), findkey);
391 if (findkey == "title" &&
392 contains(ascii_lowercase(dummy), "booktitle"))
395 } while (!found && !dummy.empty());
400 // we are not sure, if we get all, because "key= "blah, blah" is
402 // Therefore we read all until the next "=" character, which follows a
405 dummy = token(data, ',', Entries++);
406 while (!contains(dummy, '=') && !dummy.empty()) {
407 keyvalue += (',' + dummy);
408 dummy = token(data, ',', Entries++);
411 // replace double "" with originals ,, (two commas)
412 // leaving us with the all-important line
413 data = subst(keyvalue, "\"\"", ",,");
418 // 2. if there is no opening '{' then a closing '{' is probably cruft.
419 if (!contains(data, '{'))
420 data = rtrim(data, "}");
421 // happens, when last keyword
422 string::size_type const idx =
423 !data.empty() ? data.find('=') : string::npos;
425 if (idx == string::npos)
428 data = trim(data.substr(idx));
430 if (data.length() < 2 || data[0] != '=') { // a valid entry?
433 // delete '=' and the following spaces
434 data = ltrim(data, " =");
435 if (data.length() < 2) {
436 return data; // not long enough to find delimiters
438 string::size_type keypos = 1;
440 if (data[0] == '{') {
442 } else if (data[0] == '"') {
445 // no {} and no "", pure data but with a
446 // possible ',' at the end
447 return rtrim(data, ",");
449 string tmp = data.substr(keypos);
450 while (tmp.find('{') != string::npos &&
451 tmp.find('}') != string::npos &&
452 tmp.find('{') < tmp.find('}') &&
453 tmp.find('{') < tmp.find(enclosing)) {
455 keypos += tmp.find('{') + 1;
456 tmp = data.substr(keypos);
457 keypos += tmp.find('}') + 1;
458 tmp = data.substr(keypos);
460 if (tmp.find(enclosing) == string::npos)
463 keypos += tmp.find(enclosing);
464 return data.substr(1, keypos - 1);
473 using namespace biblio;
475 char const * const citeCommands[] = {
476 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
477 "citeyear", "citeyearpar" };
479 unsigned int const nCiteCommands =
480 sizeof(citeCommands) / sizeof(char *);
482 CiteStyle const citeStyles[] = {
483 CITE, CITET, CITEP, CITEALT, CITEALP,
484 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
486 unsigned int const nCiteStyles =
487 sizeof(citeStyles) / sizeof(CiteStyle);
489 CiteStyle const citeStylesFull[] = {
490 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
492 unsigned int const nCiteStylesFull =
493 sizeof(citeStylesFull) / sizeof(CiteStyle);
495 CiteStyle const citeStylesUCase[] = {
496 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
498 unsigned int const nCiteStylesUCase =
499 sizeof(citeStylesUCase) / sizeof(CiteStyle);
504 CitationStyle const getCitationStyle(string const & command)
506 if (command.empty()) return CitationStyle();
509 string cmd = command;
512 cs.forceUCase = true;
516 size_t n = cmd.size() - 1;
519 cmd = cmd.substr(0,n);
522 char const * const * const last = citeCommands + nCiteCommands;
523 char const * const * const ptr = std::find(citeCommands, last, cmd);
526 size_t idx = ptr - citeCommands;
527 cs.style = citeStyles[idx];
534 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
536 string cite = citeCommands[command];
538 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
539 if (std::find(citeStylesFull, last, command) != last)
544 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
545 if (std::find(citeStylesUCase, last, command) != last)
553 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
555 unsigned int nStyles = 1;
556 unsigned int start = 0;
558 nStyles = nCiteStyles - 1;
562 vector<CiteStyle> styles(nStyles);
564 vector<CiteStyle>::size_type i = 0;
566 for (; i != styles.size(); ++i, ++j) {
567 styles[i] = citeStyles[j];
575 getNumericalStrings(string const & key,
576 InfoMap const & map, vector<CiteStyle> const & styles)
579 return vector<string>();
582 string const author = getAbbreviatedAuthor(map, key);
583 string const year = getYear(map, key);
584 if (author.empty() || year.empty())
585 return vector<string>();
587 vector<string> vec(styles.size());
588 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
598 str = author + " [#ID]";
602 str = author + " #ID";
618 str = "(" + year + ")";
630 getAuthorYearStrings(string const & key,
631 InfoMap const & map, vector<CiteStyle> const & styles)
634 return vector<string>();
637 string const author = getAbbreviatedAuthor(map, key);
638 string const year = getYear(map, key);
639 if (author.empty() || year.empty())
640 return vector<string>();
642 vector<string> vec(styles.size());
643 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
649 str = author + " (" + year + ")";
653 str = "(" + author + ", " + year + ")";
657 str = author + " " + year ;
661 str = author + ", " + year ;
673 str = "(" + year + ")";
683 } // namespace biblio