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 #include "gettext.h" // for _()
16 #include "helper_funcs.h"
20 #include "support/lstrings.h"
21 #include "support/LAssert.h"
23 #include <boost/regex.hpp>
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 ");
95 if (authors.size() == 2)
96 return bformat(_("%1$s and %2$s"),
97 familyName(authors[0]), familyName(authors[1]));
99 if (authors.size() > 2)
100 return bformat(_("%1$s et al."), familyName(authors[0]));
102 return familyName(authors[0]);
106 string const getYear(InfoMap const & map, string const & key)
108 lyx::Assert(!map.empty());
110 InfoMap::const_iterator it = map.find(key);
113 string const & data = it->second;
115 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
116 string::size_type const pos = data.find("TheBibliographyRef");
117 if (pos != string::npos) {
123 trim(data.substr(0, pos - 1));
128 string const tmp = split(opt, authors, '(');
130 split(tmp, year, ')');
135 string year = parseBibTeX(data, "year");
145 // A functor for use with std::sort, leading to case insensitive sorting
146 struct compareNoCase: public std::binary_function<string, string, bool>
148 bool operator()(string const & s1, string const & s2) const {
149 return compare_ascii_no_case(s1, s2) < 0;
156 vector<string> const getKeys(InfoMap const & map)
158 vector<string> bibkeys;
159 InfoMap::const_iterator it = map.begin();
160 InfoMap::const_iterator end = map.end();
161 for (; it != end; ++it) {
162 bibkeys.push_back(it->first);
165 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
170 string const getInfo(InfoMap const & map, string const & key)
172 lyx::Assert(!map.empty());
174 InfoMap::const_iterator it = map.find(key);
177 string const & data = it->second;
179 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
180 string const separator("TheBibliographyRef");
181 string::size_type const pos = data.find(separator);
182 if (pos != string::npos) {
183 string::size_type const pos2 = pos + separator.size();
184 string const info = trim(data.substr(pos2));
188 // Search for all possible "required" keys
189 string author = parseBibTeX(data, "author");
191 author = parseBibTeX(data, "editor");
193 string year = parseBibTeX(data, "year");
194 string title = parseBibTeX(data, "title");
195 string booktitle = parseBibTeX(data, "booktitle");
196 string chapter = parseBibTeX(data, "chapter");
197 string number = parseBibTeX(data, "number");
198 string volume = parseBibTeX(data, "volume");
199 string pages = parseBibTeX(data, "pages");
201 string media = parseBibTeX(data, "journal");
203 media = parseBibTeX(data, "publisher");
205 media = parseBibTeX(data, "school");
207 media = parseBibTeX(data, "institution");
209 ostringstream result;
211 result << author << ", ";
214 if (!booktitle.empty())
215 result << ", in " << booktitle;
216 if (!chapter.empty())
217 result << ", Ch. " << chapter;
219 result << ", " << media;
221 result << ", vol. " << volume;
223 result << ", no. " << number;
225 result << ", pp. " << pages;
227 result << ", " << year;
229 string const result_str = rtrim(STRCONV(result.str()));
230 if (!result_str.empty())
233 // This should never happen (or at least be very unusual!)
240 // Escape special chars.
241 // All characters are literals except: '.|*?+(){}[]^$\'
242 // These characters are literals when preceded by a "\", which is done here
243 string const escape_special_chars(string const & expr)
245 // Search for all chars '.|*?+(){}[^$]\'
246 // Note that '[' and '\' must be escaped.
247 // This is a limitation of boost::regex, but all other chars in BREs
248 // are assumed literal.
249 boost::RegEx reg("[].|*?+(){}^$\\[\\\\]");
251 // $& is a perl-like expression that expands to all of the current match
252 // The '$' must be prefixed with the escape character '\' for
253 // boost to treat it as a literal.
254 // Thus, to prefix a matched expression with '\', we use:
255 string const fmt("\\\\$&");
257 return reg.Merge(expr, fmt);
261 // A functor for use with std::find_if, used to ascertain whether a
262 // data entry matches the required regex_
265 // re and icase are used to construct an instance of boost::RegEx.
266 // if icase is true, then matching is insensitive to case
267 RegexMatch(InfoMap const & m, string const & re, bool icase)
268 : map_(m), regex_(re, icase) {}
270 bool operator()(string const & key) {
274 // the data searched is the key + its associated BibTeX/biblio
277 InfoMap::const_iterator info = map_.find(key);
278 if (info != map_.end())
279 data += ' ' + info->second;
281 // Attempts to find a match for the current RE
282 // somewhere in data.
283 return regex_.Search(data);
286 bool validRE() const { return regex_.error_code() == 0; }
296 vector<string>::const_iterator
297 searchKeys(InfoMap const & theMap,
298 vector<string> const & keys,
299 string const & search_expr,
300 vector<string>::const_iterator start,
305 // Preliminary checks
306 if (start < keys.begin() || start >= keys.end())
309 string expr = trim(search_expr);
314 // We must escape special chars in the search_expr so that
315 // it is treated as a simple string by boost::regex.
316 expr = escape_special_chars(expr);
318 // Build the functor that will be passed to find_if.
319 RegexMatch const match(theMap, expr, !caseSensitive);
320 if (!match.validRE())
323 // Search the vector of 'keys' from 'start' for one that matches the
324 // predicate 'match'. Searching can be forward or backward from start.
326 return std::find_if(start, keys.end(), match);
328 vector<string>::const_reverse_iterator rit(start);
329 vector<string>::const_reverse_iterator rend = keys.rend();
330 rit = std::find_if(rit, rend, match);
334 // This is correct and always safe.
335 // (See Meyer's Effective STL, Item 28.)
336 return (++rit).base();
340 string const parseBibTeX(string data, string const & findkey)
343 // at first we delete all characters right of '%' and
344 // replace tabs through a space and remove leading spaces
345 // we read the data line by line so that the \n are
349 string dummy = token(data,'\n', Entries);
350 while (!dummy.empty()) {
351 dummy = subst(dummy, '\t', ' '); // no tabs
352 dummy = ltrim(dummy); // no leading spaces
353 // ignore lines with a beginning '%' or ignore all right of %
354 string::size_type const idx =
355 dummy.empty() ? string::npos : dummy.find('%');
356 if (idx != string::npos)
357 dummy.erase(idx, string::npos);
358 // do we have a new token or a new line of
359 // the same one? In the first case we ignore
360 // the \n and in the second we replace it
362 if (!dummy.empty()) {
363 if (!contains(dummy, "="))
364 data_ += ' ' + dummy;
368 dummy = token(data, '\n', ++Entries);
371 // replace double commas with "" for easy scanning
372 data = subst(data_, ",,", "\"\"");
378 // now get only the important line of the bibtex entry.
379 // all entries are devided by ',' except the last one.
380 data += ','; // now we have same behaviour for all entries
381 // because the last one is "blah ... }"
384 // parsing of title and booktitle is different from the
385 // others, because booktitle contains title
387 dummy = token(data, ',', Entries++);
388 if (!dummy.empty()) {
389 found = contains(ascii_lowercase(dummy), findkey);
390 if (findkey == "title" &&
391 contains(ascii_lowercase(dummy), "booktitle"))
394 } while (!found && !dummy.empty());
399 // we are not sure, if we get all, because "key= "blah, blah" is
401 // Therefore we read all until the next "=" character, which follows a
404 dummy = token(data, ',', Entries++);
405 while (!contains(dummy, '=') && !dummy.empty()) {
406 keyvalue += ',' + dummy;
407 dummy = token(data, ',', Entries++);
410 // replace double "" with originals ,, (two commas)
411 // leaving us with the all-important line
412 data = subst(keyvalue, "\"\"", ",,");
417 // 2. if there is no opening '{' then a closing '{' is probably cruft.
418 if (!contains(data, '{'))
419 data = rtrim(data, "}");
420 // happens, when last keyword
421 string::size_type const idx =
422 !data.empty() ? data.find('=') : string::npos;
424 if (idx == string::npos)
427 data = trim(data.substr(idx));
429 if (data.length() < 2 || data[0] != '=') { // a valid entry?
432 // delete '=' and the following spaces
433 data = ltrim(data, " =");
434 if (data.length() < 2) {
435 return data; // not long enough to find delimiters
437 string::size_type keypos = 1;
439 if (data[0] == '{') {
441 } else if (data[0] == '"') {
444 // no {} and no "", pure data but with a
445 // possible ',' at the end
446 return rtrim(data, ",");
448 string tmp = data.substr(keypos);
449 while (tmp.find('{') != string::npos &&
450 tmp.find('}') != string::npos &&
451 tmp.find('{') < tmp.find('}') &&
452 tmp.find('{') < tmp.find(enclosing)) {
454 keypos += tmp.find('{') + 1;
455 tmp = data.substr(keypos);
456 keypos += tmp.find('}') + 1;
457 tmp = data.substr(keypos);
459 if (tmp.find(enclosing) == string::npos)
462 keypos += tmp.find(enclosing);
463 return data.substr(1, keypos - 1);
472 using namespace biblio;
474 char const * const citeCommands[] = {
475 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
476 "citeyear", "citeyearpar" };
478 unsigned int const nCiteCommands =
479 sizeof(citeCommands) / sizeof(char *);
481 CiteStyle const citeStyles[] = {
482 CITE, CITET, CITEP, CITEALT, CITEALP,
483 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
485 unsigned int const nCiteStyles =
486 sizeof(citeStyles) / sizeof(CiteStyle);
488 CiteStyle const citeStylesFull[] = {
489 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
491 unsigned int const nCiteStylesFull =
492 sizeof(citeStylesFull) / sizeof(CiteStyle);
494 CiteStyle const citeStylesUCase[] = {
495 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
497 unsigned int const nCiteStylesUCase =
498 sizeof(citeStylesUCase) / sizeof(CiteStyle);
503 CitationStyle const getCitationStyle(string const & command)
505 if (command.empty()) return CitationStyle();
508 string cmd = command;
511 cs.forceUCase = true;
515 size_t n = cmd.size() - 1;
518 cmd = cmd.substr(0,n);
521 char const * const * const last = citeCommands + nCiteCommands;
522 char const * const * const ptr = std::find(citeCommands, last, cmd);
525 size_t idx = ptr - citeCommands;
526 cs.style = citeStyles[idx];
533 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
535 string cite = citeCommands[command];
537 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
538 if (std::find(citeStylesFull, last, command) != last)
543 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
544 if (std::find(citeStylesUCase, last, command) != last)
552 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
554 unsigned int nStyles = 1;
555 unsigned int start = 0;
557 nStyles = nCiteStyles - 1;
561 vector<CiteStyle> styles(nStyles);
563 vector<CiteStyle>::size_type i = 0;
565 for (; i != styles.size(); ++i, ++j) {
566 styles[i] = citeStyles[j];
574 getNumericalStrings(string const & key,
575 InfoMap const & map, vector<CiteStyle> const & styles)
578 return vector<string>();
581 string const author = getAbbreviatedAuthor(map, key);
582 string const year = getYear(map, key);
583 if (author.empty() || year.empty())
584 return vector<string>();
586 vector<string> vec(styles.size());
587 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
597 str = author + " [#ID]";
601 str = author + " #ID";
617 str = '(' + year + ')';
629 getAuthorYearStrings(string const & key,
630 InfoMap const & map, vector<CiteStyle> const & styles)
633 return vector<string>();
636 string const author = getAbbreviatedAuthor(map, key);
637 string const year = getYear(map, key);
638 if (author.empty() || year.empty())
639 return vector<string>();
641 vector<string> vec(styles.size());
642 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
648 str = author + " (" + year + ')';
652 str = '(' + author + ", " + year + ')';
656 str = author + ' ' + year ;
660 str = author + ", " + year ;
672 str = '(' + year + ')';
682 } // namespace biblio