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.
16 #include "support/std_sstream.h"
17 #include "gettext.h" // for _()
19 #include "support/lstrings.h"
20 #include "support/LAssert.h"
22 #include <boost/regex.hpp>
26 using namespace lyx::support;
28 using std::ostringstream;
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)
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");
86 author = parseBibTeX(data, "editor");
89 author = parseBibTeX(data, "key");
95 vector<string> const authors = getVectorFromString(author, " and ");
99 if (authors.size() == 2)
100 return bformat(_("%1$s and %2$s"),
101 familyName(authors[0]), familyName(authors[1]));
103 if (authors.size() > 2)
104 return bformat(_("%1$s et al."), familyName(authors[0]));
106 return familyName(authors[0]);
110 string const getYear(InfoMap const & map, string const & key)
112 Assert(!map.empty());
114 InfoMap::const_iterator it = map.find(key);
117 string const & data = it->second;
119 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
120 string::size_type const pos = data.find("TheBibliographyRef");
121 if (pos != string::npos) {
127 trim(data.substr(0, pos - 1));
132 string const tmp = split(opt, authors, '(');
134 split(tmp, year, ')');
139 string year = parseBibTeX(data, "year");
149 // A functor for use with std::sort, leading to case insensitive sorting
150 struct compareNoCase: public std::binary_function<string, string, bool>
152 bool operator()(string const & s1, string const & s2) const {
153 return compare_ascii_no_case(s1, s2) < 0;
160 vector<string> const getKeys(InfoMap const & map)
162 vector<string> bibkeys;
163 InfoMap::const_iterator it = map.begin();
164 InfoMap::const_iterator end = map.end();
165 for (; it != end; ++it) {
166 bibkeys.push_back(it->first);
169 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
174 string const getInfo(InfoMap const & map, string const & key)
176 Assert(!map.empty());
178 InfoMap::const_iterator it = map.find(key);
181 string const & data = it->second;
183 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
184 string const separator("TheBibliographyRef");
185 string::size_type const pos = data.find(separator);
186 if (pos != string::npos) {
187 string::size_type const pos2 = pos + separator.size();
188 string const info = trim(data.substr(pos2));
192 // Search for all possible "required" keys
193 string author = parseBibTeX(data, "author");
195 author = parseBibTeX(data, "editor");
197 string year = parseBibTeX(data, "year");
198 string title = parseBibTeX(data, "title");
199 string booktitle = parseBibTeX(data, "booktitle");
200 string chapter = parseBibTeX(data, "chapter");
201 string number = parseBibTeX(data, "number");
202 string volume = parseBibTeX(data, "volume");
203 string pages = parseBibTeX(data, "pages");
205 string media = parseBibTeX(data, "journal");
207 media = parseBibTeX(data, "publisher");
209 media = parseBibTeX(data, "school");
211 media = parseBibTeX(data, "institution");
213 ostringstream result;
215 result << author << ", ";
218 if (!booktitle.empty())
219 result << ", in " << booktitle;
220 if (!chapter.empty())
221 result << ", Ch. " << chapter;
223 result << ", " << media;
225 result << ", vol. " << volume;
227 result << ", no. " << number;
229 result << ", pp. " << pages;
231 result << ", " << year;
233 string const result_str = rtrim(STRCONV(result.str()));
234 if (!result_str.empty())
237 // This should never happen (or at least be very unusual!)
244 // Escape special chars.
245 // All characters are literals except: '.|*?+(){}[]^$\'
246 // These characters are literals when preceded by a "\", which is done here
247 string const escape_special_chars(string const & expr)
249 // Search for all chars '.|*?+(){}[^$]\'
250 // Note that '[' and '\' must be escaped.
251 // This is a limitation of boost::regex, but all other chars in BREs
252 // are assumed literal.
253 boost::RegEx reg("[].|*?+(){}^$\\[\\\\]");
255 // $& is a perl-like expression that expands to all of the current match
256 // The '$' must be prefixed with the escape character '\' for
257 // boost to treat it as a literal.
258 // Thus, to prefix a matched expression with '\', we use:
259 return STRCONV(reg.Merge(STRCONV(expr), "\\\\$&"));
263 // A functor for use with std::find_if, used to ascertain whether a
264 // data entry matches the required regex_
267 // re and icase are used to construct an instance of boost::RegEx.
268 // if icase is true, then matching is insensitive to case
269 RegexMatch(InfoMap const & m, string const & re, bool icase)
270 : map_(m), regex_(STRCONV(re), icase) {}
272 bool operator()(string const & key) {
276 // the data searched is the key + its associated BibTeX/biblio
279 InfoMap::const_iterator info = map_.find(key);
280 if (info != map_.end())
281 data += ' ' + info->second;
283 // Attempts to find a match for the current RE
284 // somewhere in data.
285 return regex_.Search(STRCONV(data));
288 bool validRE() const { return regex_.error_code() == 0; }
298 vector<string>::const_iterator
299 searchKeys(InfoMap const & theMap,
300 vector<string> const & keys,
301 string const & search_expr,
302 vector<string>::const_iterator start,
307 // Preliminary checks
308 if (start < keys.begin() || start >= keys.end())
311 string expr = trim(search_expr);
316 // We must escape special chars in the search_expr so that
317 // it is treated as a simple string by boost::regex.
318 expr = escape_special_chars(expr);
320 // Build the functor that will be passed to find_if.
321 RegexMatch const match(theMap, expr, !caseSensitive);
322 if (!match.validRE())
325 // Search the vector of 'keys' from 'start' for one that matches the
326 // predicate 'match'. Searching can be forward or backward from start.
328 return std::find_if(start, keys.end(), match);
330 vector<string>::const_reverse_iterator rit(start);
331 vector<string>::const_reverse_iterator rend = keys.rend();
332 rit = std::find_if(rit, rend, match);
336 // This is correct and always safe.
337 // (See Meyer's Effective STL, Item 28.)
338 return (++rit).base();
342 string const parseBibTeX(string data, string const & findkey)
345 // at first we delete all characters right of '%' and
346 // replace tabs through a space and remove leading spaces
347 // we read the data line by line so that the \n are
351 string dummy = token(data,'\n', Entries);
352 while (!dummy.empty()) {
353 dummy = subst(dummy, '\t', ' '); // no tabs
354 dummy = ltrim(dummy); // no leading spaces
355 // ignore lines with a beginning '%' or ignore all right of %
356 string::size_type const idx =
357 dummy.empty() ? string::npos : dummy.find('%');
358 if (idx != string::npos)
359 dummy.erase(idx, string::npos);
360 // do we have a new token or a new line of
361 // the same one? In the first case we ignore
362 // the \n and in the second we replace it
364 if (!dummy.empty()) {
365 if (!contains(dummy, "="))
366 data_ += ' ' + dummy;
370 dummy = token(data, '\n', ++Entries);
373 // replace double commas with "" for easy scanning
374 data = subst(data_, ",,", "\"\"");
380 // now get only the important line of the bibtex entry.
381 // all entries are devided by ',' except the last one.
382 data += ','; // now we have same behaviour for all entries
383 // because the last one is "blah ... }"
386 // parsing of title and booktitle is different from the
387 // others, because booktitle contains title
389 dummy = token(data, ',', Entries++);
390 if (!dummy.empty()) {
391 found = contains(ascii_lowercase(dummy), findkey);
392 if (findkey == "title" &&
393 contains(ascii_lowercase(dummy), "booktitle"))
396 } while (!found && !dummy.empty());
401 // we are not sure, if we get all, because "key= "blah, blah" is
403 // Therefore we read all until the next "=" character, which follows a
406 dummy = token(data, ',', Entries++);
407 while (!contains(dummy, '=') && !dummy.empty()) {
408 keyvalue += ',' + dummy;
409 dummy = token(data, ',', Entries++);
412 // replace double "" with originals ,, (two commas)
413 // leaving us with the all-important line
414 data = subst(keyvalue, "\"\"", ",,");
419 // 2. if there is no opening '{' then a closing '{' is probably cruft.
420 if (!contains(data, '{'))
421 data = rtrim(data, "}");
422 // happens, when last keyword
423 string::size_type const idx =
424 !data.empty() ? data.find('=') : string::npos;
426 if (idx == string::npos)
429 data = trim(data.substr(idx));
431 if (data.length() < 2 || data[0] != '=') { // a valid entry?
434 // delete '=' and the following spaces
435 data = ltrim(data, " =");
436 if (data.length() < 2) {
437 return data; // not long enough to find delimiters
439 string::size_type keypos = 1;
441 if (data[0] == '{') {
443 } else if (data[0] == '"') {
446 // no {} and no "", pure data but with a
447 // possible ',' at the end
448 return rtrim(data, ",");
450 string tmp = data.substr(keypos);
451 while (tmp.find('{') != string::npos &&
452 tmp.find('}') != string::npos &&
453 tmp.find('{') < tmp.find('}') &&
454 tmp.find('{') < tmp.find(enclosing)) {
456 keypos += tmp.find('{') + 1;
457 tmp = data.substr(keypos);
458 keypos += tmp.find('}') + 1;
459 tmp = data.substr(keypos);
461 if (tmp.find(enclosing) == string::npos)
464 keypos += tmp.find(enclosing);
465 return data.substr(1, keypos - 1);
474 using namespace biblio;
476 char const * const citeCommands[] = {
477 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
478 "citeyear", "citeyearpar" };
480 unsigned int const nCiteCommands =
481 sizeof(citeCommands) / sizeof(char *);
483 CiteStyle const citeStyles[] = {
484 CITE, CITET, CITEP, CITEALT, CITEALP,
485 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
487 unsigned int const nCiteStyles =
488 sizeof(citeStyles) / sizeof(CiteStyle);
490 CiteStyle const citeStylesFull[] = {
491 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
493 unsigned int const nCiteStylesFull =
494 sizeof(citeStylesFull) / sizeof(CiteStyle);
496 CiteStyle const citeStylesUCase[] = {
497 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
499 unsigned int const nCiteStylesUCase =
500 sizeof(citeStylesUCase) / sizeof(CiteStyle);
505 CitationStyle const getCitationStyle(string const & command)
507 if (command.empty()) return CitationStyle();
510 string cmd = command;
513 cs.forceUCase = true;
517 size_t n = cmd.size() - 1;
520 cmd = cmd.substr(0,n);
523 char const * const * const last = citeCommands + nCiteCommands;
524 char const * const * const ptr = std::find(citeCommands, last, cmd);
527 size_t idx = ptr - citeCommands;
528 cs.style = citeStyles[idx];
535 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
537 string cite = citeCommands[command];
539 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
540 if (std::find(citeStylesFull, last, command) != last)
545 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
546 if (std::find(citeStylesUCase, last, command) != last)
554 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
556 unsigned int nStyles = 1;
557 unsigned int start = 0;
559 nStyles = nCiteStyles - 1;
563 vector<CiteStyle> styles(nStyles);
565 vector<CiteStyle>::size_type i = 0;
567 for (; i != styles.size(); ++i, ++j) {
568 styles[i] = citeStyles[j];
576 getNumericalStrings(string const & key,
577 InfoMap const & map, vector<CiteStyle> const & styles)
580 return vector<string>();
583 string const author = getAbbreviatedAuthor(map, key);
584 string const year = getYear(map, key);
585 if (author.empty() || year.empty())
586 return vector<string>();
588 vector<string> vec(styles.size());
589 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
599 str = author + " [#ID]";
603 str = author + " #ID";
619 str = '(' + year + ')';
631 getAuthorYearStrings(string const & key,
632 InfoMap const & map, vector<CiteStyle> const & styles)
635 return vector<string>();
638 string const author = getAbbreviatedAuthor(map, key);
639 string const year = getYear(map, key);
640 if (author.empty() || year.empty())
641 return vector<string>();
643 vector<string> vec(styles.size());
644 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
650 str = author + " (" + year + ')';
654 str = '(' + author + ", " + year + ')';
658 str = author + ' ' + year ;
662 str = author + ", " + year ;
674 str = '(' + year + ')';
684 } // namespace biblio