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"
22 #include "support/lstrings.h"
23 #include "support/LAssert.h"
25 #include <boost/regex.hpp>
29 using namespace lyx::support;
36 string const familyName(string const & name)
41 // possible authorname combinations are:
42 // "Surname, FirstName"
44 // "FirstName Surname"
46 string::size_type idx = fname.find(',');
47 if (idx != string::npos)
48 return ltrim(fname.substr(0, idx));
49 idx = fname.rfind('.');
50 if (idx != string::npos)
51 fname = ltrim(fname.substr(idx + 1));
52 // test if we have a LaTeX Space in front
54 return fname.substr(2);
60 string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
64 InfoMap::const_iterator it = map.find(key);
67 string const & data = it->second;
69 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
70 string::size_type const pos = data.find("TheBibliographyRef");
71 if (pos != string::npos) {
76 string const opt = trim(data.substr(0, pos - 1));
81 split(opt, authors, '(');
85 string author = parseBibTeX(data, "author");
88 author = parseBibTeX(data, "editor");
91 author = parseBibTeX(data, "key");
97 vector<string> const authors = getVectorFromString(author, " and ");
101 if (authors.size() == 2)
102 return bformat(_("%1$s and %2$s"),
103 familyName(authors[0]), familyName(authors[1]));
105 if (authors.size() > 2)
106 return bformat(_("%1$s et al."), familyName(authors[0]));
108 return familyName(authors[0]);
112 string const getYear(InfoMap const & map, string const & key)
114 Assert(!map.empty());
116 InfoMap::const_iterator it = map.find(key);
119 string const & data = it->second;
121 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
122 string::size_type const pos = data.find("TheBibliographyRef");
123 if (pos != string::npos) {
129 trim(data.substr(0, pos - 1));
134 string const tmp = split(opt, authors, '(');
136 split(tmp, year, ')');
141 string year = parseBibTeX(data, "year");
151 // A functor for use with std::sort, leading to case insensitive sorting
152 struct compareNoCase: public std::binary_function<string, string, bool>
154 bool operator()(string const & s1, string const & s2) const {
155 return compare_ascii_no_case(s1, s2) < 0;
162 vector<string> const getKeys(InfoMap const & map)
164 vector<string> bibkeys;
165 InfoMap::const_iterator it = map.begin();
166 InfoMap::const_iterator end = map.end();
167 for (; it != end; ++it) {
168 bibkeys.push_back(it->first);
171 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
176 string const getInfo(InfoMap const & map, string const & key)
178 Assert(!map.empty());
180 InfoMap::const_iterator it = map.find(key);
183 string const & data = it->second;
185 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
186 string const separator("TheBibliographyRef");
187 string::size_type const pos = data.find(separator);
188 if (pos != string::npos) {
189 string::size_type const pos2 = pos + separator.size();
190 string const info = trim(data.substr(pos2));
194 // Search for all possible "required" keys
195 string author = parseBibTeX(data, "author");
197 author = parseBibTeX(data, "editor");
199 string year = parseBibTeX(data, "year");
200 string title = parseBibTeX(data, "title");
201 string booktitle = parseBibTeX(data, "booktitle");
202 string chapter = parseBibTeX(data, "chapter");
203 string number = parseBibTeX(data, "number");
204 string volume = parseBibTeX(data, "volume");
205 string pages = parseBibTeX(data, "pages");
207 string media = parseBibTeX(data, "journal");
209 media = parseBibTeX(data, "publisher");
211 media = parseBibTeX(data, "school");
213 media = parseBibTeX(data, "institution");
215 ostringstream result;
217 result << author << ", ";
220 if (!booktitle.empty())
221 result << ", in " << booktitle;
222 if (!chapter.empty())
223 result << ", Ch. " << chapter;
225 result << ", " << media;
227 result << ", vol. " << volume;
229 result << ", no. " << number;
231 result << ", pp. " << pages;
233 result << ", " << year;
235 string const result_str = rtrim(STRCONV(result.str()));
236 if (!result_str.empty())
239 // This should never happen (or at least be very unusual!)
246 // Escape special chars.
247 // All characters are literals except: '.|*?+(){}[]^$\'
248 // These characters are literals when preceded by a "\", which is done here
249 string const escape_special_chars(string const & expr)
251 // Search for all chars '.|*?+(){}[^$]\'
252 // Note that '[' and '\' must be escaped.
253 // This is a limitation of boost::regex, but all other chars in BREs
254 // are assumed literal.
255 boost::RegEx reg("[].|*?+(){}^$\\[\\\\]");
257 // $& is a perl-like expression that expands to all of the current match
258 // The '$' must be prefixed with the escape character '\' for
259 // boost to treat it as a literal.
260 // Thus, to prefix a matched expression with '\', we use:
261 return STRCONV(reg.Merge(STRCONV(expr), "\\\\$&"));
265 // A functor for use with std::find_if, used to ascertain whether a
266 // data entry matches the required regex_
269 // re and icase are used to construct an instance of boost::RegEx.
270 // if icase is true, then matching is insensitive to case
271 RegexMatch(InfoMap const & m, string const & re, bool icase)
272 : map_(m), regex_(STRCONV(re), icase) {}
274 bool operator()(string const & key) {
278 // the data searched is the key + its associated BibTeX/biblio
281 InfoMap::const_iterator info = map_.find(key);
282 if (info != map_.end())
283 data += ' ' + info->second;
285 // Attempts to find a match for the current RE
286 // somewhere in data.
287 return regex_.Search(STRCONV(data));
290 bool validRE() const { return regex_.error_code() == 0; }
300 vector<string>::const_iterator
301 searchKeys(InfoMap const & theMap,
302 vector<string> const & keys,
303 string const & search_expr,
304 vector<string>::const_iterator start,
309 // Preliminary checks
310 if (start < keys.begin() || start >= keys.end())
313 string expr = trim(search_expr);
318 // We must escape special chars in the search_expr so that
319 // it is treated as a simple string by boost::regex.
320 expr = escape_special_chars(expr);
322 // Build the functor that will be passed to find_if.
323 RegexMatch const match(theMap, expr, !caseSensitive);
324 if (!match.validRE())
327 // Search the vector of 'keys' from 'start' for one that matches the
328 // predicate 'match'. Searching can be forward or backward from start.
330 return std::find_if(start, keys.end(), match);
332 vector<string>::const_reverse_iterator rit(start);
333 vector<string>::const_reverse_iterator rend = keys.rend();
334 rit = std::find_if(rit, rend, match);
338 // This is correct and always safe.
339 // (See Meyer's Effective STL, Item 28.)
340 return (++rit).base();
344 string const parseBibTeX(string data, string const & findkey)
347 // at first we delete all characters right of '%' and
348 // replace tabs through a space and remove leading spaces
349 // we read the data line by line so that the \n are
353 string dummy = token(data,'\n', Entries);
354 while (!dummy.empty()) {
355 dummy = subst(dummy, '\t', ' '); // no tabs
356 dummy = ltrim(dummy); // no leading spaces
357 // ignore lines with a beginning '%' or ignore all right of %
358 string::size_type const idx =
359 dummy.empty() ? string::npos : dummy.find('%');
360 if (idx != string::npos)
361 dummy.erase(idx, string::npos);
362 // do we have a new token or a new line of
363 // the same one? In the first case we ignore
364 // the \n and in the second we replace it
366 if (!dummy.empty()) {
367 if (!contains(dummy, "="))
368 data_ += ' ' + dummy;
372 dummy = token(data, '\n', ++Entries);
375 // replace double commas with "" for easy scanning
376 data = subst(data_, ",,", "\"\"");
382 // now get only the important line of the bibtex entry.
383 // all entries are devided by ',' except the last one.
384 data += ','; // now we have same behaviour for all entries
385 // because the last one is "blah ... }"
388 // parsing of title and booktitle is different from the
389 // others, because booktitle contains title
391 dummy = token(data, ',', Entries++);
392 if (!dummy.empty()) {
393 found = contains(ascii_lowercase(dummy), findkey);
394 if (findkey == "title" &&
395 contains(ascii_lowercase(dummy), "booktitle"))
398 } while (!found && !dummy.empty());
403 // we are not sure, if we get all, because "key= "blah, blah" is
405 // Therefore we read all until the next "=" character, which follows a
408 dummy = token(data, ',', Entries++);
409 while (!contains(dummy, '=') && !dummy.empty()) {
410 keyvalue += ',' + dummy;
411 dummy = token(data, ',', Entries++);
414 // replace double "" with originals ,, (two commas)
415 // leaving us with the all-important line
416 data = subst(keyvalue, "\"\"", ",,");
421 // 2. if there is no opening '{' then a closing '{' is probably cruft.
422 if (!contains(data, '{'))
423 data = rtrim(data, "}");
424 // happens, when last keyword
425 string::size_type const idx =
426 !data.empty() ? data.find('=') : string::npos;
428 if (idx == string::npos)
431 data = trim(data.substr(idx));
433 if (data.length() < 2 || data[0] != '=') { // a valid entry?
436 // delete '=' and the following spaces
437 data = ltrim(data, " =");
438 if (data.length() < 2) {
439 return data; // not long enough to find delimiters
441 string::size_type keypos = 1;
443 if (data[0] == '{') {
445 } else if (data[0] == '"') {
448 // no {} and no "", pure data but with a
449 // possible ',' at the end
450 return rtrim(data, ",");
452 string tmp = data.substr(keypos);
453 while (tmp.find('{') != string::npos &&
454 tmp.find('}') != string::npos &&
455 tmp.find('{') < tmp.find('}') &&
456 tmp.find('{') < tmp.find(enclosing)) {
458 keypos += tmp.find('{') + 1;
459 tmp = data.substr(keypos);
460 keypos += tmp.find('}') + 1;
461 tmp = data.substr(keypos);
463 if (tmp.find(enclosing) == string::npos)
466 keypos += tmp.find(enclosing);
467 return data.substr(1, keypos - 1);
476 using namespace biblio;
478 char const * const citeCommands[] = {
479 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
480 "citeyear", "citeyearpar" };
482 unsigned int const nCiteCommands =
483 sizeof(citeCommands) / sizeof(char *);
485 CiteStyle const citeStyles[] = {
486 CITE, CITET, CITEP, CITEALT, CITEALP,
487 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
489 unsigned int const nCiteStyles =
490 sizeof(citeStyles) / sizeof(CiteStyle);
492 CiteStyle const citeStylesFull[] = {
493 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
495 unsigned int const nCiteStylesFull =
496 sizeof(citeStylesFull) / sizeof(CiteStyle);
498 CiteStyle const citeStylesUCase[] = {
499 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
501 unsigned int const nCiteStylesUCase =
502 sizeof(citeStylesUCase) / sizeof(CiteStyle);
507 CitationStyle const getCitationStyle(string const & command)
509 if (command.empty()) return CitationStyle();
512 string cmd = command;
515 cs.forceUCase = true;
519 size_t n = cmd.size() - 1;
522 cmd = cmd.substr(0,n);
525 char const * const * const last = citeCommands + nCiteCommands;
526 char const * const * const ptr = std::find(citeCommands, last, cmd);
529 size_t idx = ptr - citeCommands;
530 cs.style = citeStyles[idx];
537 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
539 string cite = citeCommands[command];
541 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
542 if (std::find(citeStylesFull, last, command) != last)
547 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
548 if (std::find(citeStylesUCase, last, command) != last)
556 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
558 unsigned int nStyles = 1;
559 unsigned int start = 0;
561 nStyles = nCiteStyles - 1;
565 vector<CiteStyle> styles(nStyles);
567 vector<CiteStyle>::size_type i = 0;
569 for (; i != styles.size(); ++i, ++j) {
570 styles[i] = citeStyles[j];
578 getNumericalStrings(string const & key,
579 InfoMap const & map, vector<CiteStyle> const & styles)
582 return vector<string>();
585 string const author = getAbbreviatedAuthor(map, key);
586 string const year = getYear(map, key);
587 if (author.empty() || year.empty())
588 return vector<string>();
590 vector<string> vec(styles.size());
591 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
601 str = author + " [#ID]";
605 str = author + " #ID";
621 str = '(' + year + ')';
633 getAuthorYearStrings(string const & key,
634 InfoMap const & map, vector<CiteStyle> const & styles)
637 return vector<string>();
640 string const author = getAbbreviatedAuthor(map, key);
641 string const year = getYear(map, key);
642 if (author.empty() || year.empty())
643 return vector<string>();
645 vector<string> vec(styles.size());
646 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
652 str = author + " (" + year + ')';
656 str = '(' + author + ", " + year + ')';
660 str = author + ' ' + year ;
664 str = author + ", " + year ;
676 str = '(' + year + ')';
686 } // namespace biblio