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 they must be escaped in the RE.
248 boost::RegEx reg("[\\.\\|\\*\\?\\+\\(\\)\\{\\}\\[\\]\\^\\$\\\\]");
250 // $& is a perl-like expression that expands to all of the current match
251 // The '$' must be prefixed with the escape character '\' for
252 // boost to treat it as a literal.
253 // Thus, to prefix a matched expression with '\', we use:
254 string const fmt("\\\\$&");
256 return reg.Merge(expr, fmt);
260 // A functor for use with std::find_if, used to ascertain whether a
261 // data entry matches the required regex_
264 // re and icase are used to construct an instance of boost::RegEx.
265 // if icase is true, then matching is insensitive to case
266 RegexMatch(InfoMap const & m, string const & re, bool icase)
267 : map_(m), regex_(re, icase) {}
269 bool operator()(string const & key) {
273 // the data searched is the key + its associated BibTeX/biblio
276 InfoMap::const_iterator info = map_.find(key);
277 if (info != map_.end())
278 data += " " + info->second;
280 // Attempts to find a match for the current RE
281 // somewhere in data.
282 return regex_.Search(data);
285 bool validRE() const { return regex_.error_code() == 0; }
295 vector<string>::const_iterator
296 searchKeys(InfoMap const & theMap,
297 vector<string> const & keys,
298 string const & search_expr,
299 vector<string>::const_iterator start,
304 // Preliminary checks
305 if (start < keys.begin() || start >= keys.end())
308 string expr = trim(search_expr);
313 // We must escape special chars in the search_expr so that
314 // it is treated as a simple string by boost::regex.
315 expr = escape_special_chars(expr);
317 // Build the functor that will be passed to find_if.
318 RegexMatch const match(theMap, expr, !caseSensitive);
319 if (!match.validRE())
322 // Search the vector of 'keys' from 'start' for one that matches the
323 // predicate 'match'. Searching can be forward or backward from start.
325 return std::find_if(start, keys.end(), match);
327 vector<string>::const_reverse_iterator rit(start);
328 vector<string>::const_reverse_iterator rend = keys.rend();
329 rit = std::find_if(rit, rend, match);
333 // This is correct and always safe.
334 // (See Meyer's Effective STL, Item 28.)
335 return (++rit).base();
339 string const parseBibTeX(string data, string const & findkey)
342 // at first we delete all characters right of '%' and
343 // replace tabs through a space and remove leading spaces
344 // we read the data line by line so that the \n are
348 string dummy = token(data,'\n', Entries);
349 while (!dummy.empty()) {
350 dummy = subst(dummy, '\t', ' '); // no tabs
351 dummy = ltrim(dummy); // no leading spaces
352 // ignore lines with a beginning '%' or ignore all right of %
353 string::size_type const idx =
354 dummy.empty() ? string::npos : dummy.find('%');
355 if (idx != string::npos)
356 dummy.erase(idx, string::npos);
357 // do we have a new token or a new line of
358 // the same one? In the first case we ignore
359 // the \n and in the second we replace it
361 if (!dummy.empty()) {
362 if (!contains(dummy, "="))
363 data_ += (' ' + dummy);
367 dummy = token(data, '\n', ++Entries);
370 // replace double commas with "" for easy scanning
371 data = subst(data_, ",,", "\"\"");
377 // now get only the important line of the bibtex entry.
378 // all entries are devided by ',' except the last one.
379 data += ','; // now we have same behaviour for all entries
380 // because the last one is "blah ... }"
383 // parsing of title and booktitle is different from the
384 // others, because booktitle contains title
386 dummy = token(data, ',', Entries++);
387 if (!dummy.empty()) {
388 found = contains(ascii_lowercase(dummy), findkey);
389 if (findkey == "title" &&
390 contains(ascii_lowercase(dummy), "booktitle"))
393 } while (!found && !dummy.empty());
398 // we are not sure, if we get all, because "key= "blah, blah" is
400 // Therefore we read all until the next "=" character, which follows a
403 dummy = token(data, ',', Entries++);
404 while (!contains(dummy, '=') && !dummy.empty()) {
405 keyvalue += (',' + dummy);
406 dummy = token(data, ',', Entries++);
409 // replace double "" with originals ,, (two commas)
410 // leaving us with the all-important line
411 data = subst(keyvalue, "\"\"", ",,");
416 // 2. if there is no opening '{' then a closing '{' is probably cruft.
417 if (!contains(data, '{'))
418 data = rtrim(data, "}");
419 // happens, when last keyword
420 string::size_type const idx =
421 !data.empty() ? data.find('=') : string::npos;
423 if (idx == string::npos)
426 data = trim(data.substr(idx));
428 if (data.length() < 2 || data[0] != '=') { // a valid entry?
431 // delete '=' and the following spaces
432 data = ltrim(data, " =");
433 if (data.length() < 2) {
434 return data; // not long enough to find delimiters
436 string::size_type keypos = 1;
438 if (data[0] == '{') {
440 } else if (data[0] == '"') {
443 // no {} and no "", pure data but with a
444 // possible ',' at the end
445 return rtrim(data, ",");
447 string tmp = data.substr(keypos);
448 while (tmp.find('{') != string::npos &&
449 tmp.find('}') != string::npos &&
450 tmp.find('{') < tmp.find('}') &&
451 tmp.find('{') < tmp.find(enclosing)) {
453 keypos += tmp.find('{') + 1;
454 tmp = data.substr(keypos);
455 keypos += tmp.find('}') + 1;
456 tmp = data.substr(keypos);
458 if (tmp.find(enclosing) == string::npos)
461 keypos += tmp.find(enclosing);
462 return data.substr(1, keypos - 1);
471 using namespace biblio;
473 char const * const citeCommands[] = {
474 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
475 "citeyear", "citeyearpar" };
477 unsigned int const nCiteCommands =
478 sizeof(citeCommands) / sizeof(char *);
480 CiteStyle const citeStyles[] = {
481 CITE, CITET, CITEP, CITEALT, CITEALP,
482 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
484 unsigned int const nCiteStyles =
485 sizeof(citeStyles) / sizeof(CiteStyle);
487 CiteStyle const citeStylesFull[] = {
488 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
490 unsigned int const nCiteStylesFull =
491 sizeof(citeStylesFull) / sizeof(CiteStyle);
493 CiteStyle const citeStylesUCase[] = {
494 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
496 unsigned int const nCiteStylesUCase =
497 sizeof(citeStylesUCase) / sizeof(CiteStyle);
502 CitationStyle const getCitationStyle(string const & command)
504 if (command.empty()) return CitationStyle();
507 string cmd = command;
510 cs.forceUCase = true;
514 size_t n = cmd.size() - 1;
517 cmd = cmd.substr(0,n);
520 char const * const * const last = citeCommands + nCiteCommands;
521 char const * const * const ptr = std::find(citeCommands, last, cmd);
524 size_t idx = ptr - citeCommands;
525 cs.style = citeStyles[idx];
532 string const getCiteCommand(CiteStyle command, bool full, bool forceUCase)
534 string cite = citeCommands[command];
536 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
537 if (std::find(citeStylesFull, last, command) != last)
542 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
543 if (std::find(citeStylesUCase, last, command) != last)
551 vector<CiteStyle> const getCiteStyles(bool usingNatbib)
553 unsigned int nStyles = 1;
554 unsigned int start = 0;
556 nStyles = nCiteStyles - 1;
560 vector<CiteStyle> styles(nStyles);
562 vector<CiteStyle>::size_type i = 0;
564 for (; i != styles.size(); ++i, ++j) {
565 styles[i] = citeStyles[j];
573 getNumericalStrings(string const & key,
574 InfoMap const & map, vector<CiteStyle> const & styles)
577 return vector<string>();
580 string const author = getAbbreviatedAuthor(map, key);
581 string const year = getYear(map, key);
582 if (author.empty() || year.empty())
583 return vector<string>();
585 vector<string> vec(styles.size());
586 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
596 str = author + " [#ID]";
600 str = author + " #ID";
616 str = "(" + year + ")";
628 getAuthorYearStrings(string const & key,
629 InfoMap const & map, vector<CiteStyle> const & styles)
632 return vector<string>();
635 string const author = getAbbreviatedAuthor(map, key);
636 string const year = getYear(map, key);
637 if (author.empty() || year.empty())
638 return vector<string>();
640 vector<string> vec(styles.size());
641 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
647 str = author + " (" + year + ")";
651 str = "(" + author + ", " + year + ")";
655 str = author + " " + year ;
659 str = author + ", " + year ;
671 str = "(" + year + ")";
681 } // namespace biblio