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 "bufferparams.h"
20 #include "support/lstrings.h"
22 #include <boost/regex.hpp>
28 using std::ostringstream;
34 using support::ascii_lowercase;
35 using support::bformat;
36 using support::compare_ascii_no_case;
37 using support::contains;
38 using support::getVectorFromString;
40 using support::prefixIs;
51 vector<string> const init_possible_cite_commands()
53 char const * const pos[] = {
55 "citet", "citep", "citealt", "citealp",
56 "citeauthor", "citeyear", "citeyearpar",
57 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
58 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
59 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
61 "footcite", "footcitet", "footcitep", "footcitealt",
62 "footcitealp", "footciteauthor", "footciteyear",
68 size_t const size_pos = sizeof(pos) / sizeof(pos[0]);
70 return vector<string>(pos, pos + size_pos);
74 vector<string> const & possible_cite_commands()
76 static vector<string> const pos = init_possible_cite_commands();
81 bool is_possible_cite_command(string const & input)
83 vector<string> const & possibles = possible_cite_commands();
84 vector<string>::const_iterator const end = possibles.end();
85 return std::find(possibles.begin(), end, input) != end;
89 string const default_cite_command(CiteEngine engine)
96 case ENGINE_NATBIB_AUTHORYEAR:
99 case ENGINE_NATBIB_NUMERICAL:
112 string const asValidLatexCommand(string const & input,
113 CiteEngine_enum const & engine)
115 string const default_str = default_cite_command(engine);
116 if (!is_possible_cite_command(input))
122 output = default_str;
125 case ENGINE_NATBIB_AUTHORYEAR:
126 case ENGINE_NATBIB_NUMERICAL:
127 if (input == "cite" || input == "citefield" ||
128 input == "citetitle" || input == "cite*")
129 output = default_str;
130 else if (prefixIs(input, "foot"))
131 output = input.substr(4);
136 case ENGINE_JURABIB: {
137 // Jurabib does not support the 'uppercase' natbib style.
139 output = string(1, 'c') + input.substr(1);
143 // Jurabib does not support the 'full' natbib style.
144 string::size_type const n = output.size() - 1;
145 if (output != "cite*" && output[n] == '*')
146 output = output.substr(0, n);
156 string const familyName(string const & name)
158 // Very simple parser
161 // possible authorname combinations are:
162 // "Surname, FirstName"
164 // "FirstName Surname"
166 string::size_type idx = fname.find(',');
167 if (idx != string::npos)
168 return ltrim(fname.substr(0, idx));
169 idx = fname.rfind('.');
170 if (idx != string::npos)
171 fname = ltrim(fname.substr(idx + 1));
172 // test if we have a LaTeX Space in front
173 if (fname[0] == '\\')
174 return fname.substr(2);
180 string const getAbbreviatedAuthor(InfoMap const & map, string const & key)
182 BOOST_ASSERT(!map.empty());
184 InfoMap::const_iterator it = map.find(key);
187 string const & data = it->second;
189 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
190 string::size_type const pos = data.find("TheBibliographyRef");
191 if (pos != string::npos) {
196 string const opt = trim(data.substr(0, pos - 1));
201 split(opt, authors, '(');
205 string author = parseBibTeX(data, "author");
208 author = parseBibTeX(data, "editor");
210 if (author.empty()) {
211 author = parseBibTeX(data, "key");
217 vector<string> const authors = getVectorFromString(author, " and ");
221 if (authors.size() == 2)
222 return bformat(_("%1$s and %2$s"),
223 familyName(authors[0]), familyName(authors[1]));
225 if (authors.size() > 2)
226 return bformat(_("%1$s et al."), familyName(authors[0]));
228 return familyName(authors[0]);
232 string const getYear(InfoMap const & map, string const & key)
234 BOOST_ASSERT(!map.empty());
236 InfoMap::const_iterator it = map.find(key);
239 string const & data = it->second;
241 // Is the entry a BibTeX one or one from lyx-layout "bibliography"?
242 string::size_type const pos = data.find("TheBibliographyRef");
243 if (pos != string::npos) {
249 trim(data.substr(0, pos - 1));
254 string const tmp = split(opt, authors, '(');
256 split(tmp, year, ')');
261 string year = parseBibTeX(data, "year");
271 // A functor for use with std::sort, leading to case insensitive sorting
272 class compareNoCase: public std::binary_function<string, string, bool>
275 bool operator()(string const & s1, string const & s2) const {
276 return compare_ascii_no_case(s1, s2) < 0;
283 vector<string> const getKeys(InfoMap const & map)
285 vector<string> bibkeys;
286 InfoMap::const_iterator it = map.begin();
287 InfoMap::const_iterator end = map.end();
288 for (; it != end; ++it) {
289 bibkeys.push_back(it->first);
292 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
297 string const getInfo(InfoMap const & map, string const & key)
299 BOOST_ASSERT(!map.empty());
301 InfoMap::const_iterator it = map.find(key);
304 string const & data = it->second;
306 // is the entry a BibTeX one or one from lyx-layout "bibliography"?
307 string const separator("TheBibliographyRef");
308 string::size_type const pos = data.find(separator);
309 if (pos != string::npos) {
310 string::size_type const pos2 = pos + separator.size();
311 string const info = trim(data.substr(pos2));
315 // Search for all possible "required" keys
316 string author = parseBibTeX(data, "author");
318 author = parseBibTeX(data, "editor");
320 string year = parseBibTeX(data, "year");
321 string title = parseBibTeX(data, "title");
322 string booktitle = parseBibTeX(data, "booktitle");
323 string chapter = parseBibTeX(data, "chapter");
324 string number = parseBibTeX(data, "number");
325 string volume = parseBibTeX(data, "volume");
326 string pages = parseBibTeX(data, "pages");
327 string annote = parseBibTeX(data, "annote");
329 string media = parseBibTeX(data, "journal");
331 media = parseBibTeX(data, "publisher");
333 media = parseBibTeX(data, "school");
335 media = parseBibTeX(data, "institution");
337 ostringstream result;
339 result << author << ", ";
342 if (!booktitle.empty())
343 result << ", in " << booktitle;
344 if (!chapter.empty())
345 result << ", Ch. " << chapter;
347 result << ", " << media;
349 result << ", vol. " << volume;
351 result << ", no. " << number;
353 result << ", pp. " << pages;
355 result << ", " << year;
357 result << "\n\n" << annote;
359 string const result_str = rtrim(result.str());
360 if (!result_str.empty())
363 // This should never happen (or at least be very unusual!)
370 // Escape special chars.
371 // All characters are literals except: '.|*?+(){}[]^$\'
372 // These characters are literals when preceded by a "\", which is done here
373 string const escape_special_chars(string const & expr)
375 // Search for all chars '.|*?+(){}[^$]\'
376 // Note that '[' and '\' must be escaped.
377 // This is a limitation of boost::regex, but all other chars in BREs
378 // are assumed literal.
379 boost::RegEx reg("[].|*?+(){}^$\\[\\\\]");
381 // $& is a perl-like expression that expands to all of the current match
382 // The '$' must be prefixed with the escape character '\' for
383 // boost to treat it as a literal.
384 // Thus, to prefix a matched expression with '\', we use:
385 return reg.Merge(expr, "\\\\$&");
389 // A functor for use with std::find_if, used to ascertain whether a
390 // data entry matches the required regex_
391 class RegexMatch : public std::unary_function<string, bool>
394 // re and icase are used to construct an instance of boost::RegEx.
395 // if icase is true, then matching is insensitive to case
396 RegexMatch(InfoMap const & m, string const & re, bool icase)
397 : map_(m), regex_(re, icase) {}
399 bool operator()(string const & key) const {
403 // the data searched is the key + its associated BibTeX/biblio
406 InfoMap::const_iterator info = map_.find(key);
407 if (info != map_.end())
408 data += ' ' + info->second;
410 // Attempts to find a match for the current RE
411 // somewhere in data.
412 return regex_.Search(data);
415 bool validRE() const { return regex_.error_code() == 0; }
419 mutable boost::RegEx regex_;
425 vector<string>::const_iterator
426 searchKeys(InfoMap const & theMap,
427 vector<string> const & keys,
428 string const & search_expr,
429 vector<string>::const_iterator start,
434 // Preliminary checks
435 if (start < keys.begin() || start >= keys.end())
438 string expr = trim(search_expr);
443 // We must escape special chars in the search_expr so that
444 // it is treated as a simple string by boost::regex.
445 expr = escape_special_chars(expr);
447 // Build the functor that will be passed to find_if.
448 RegexMatch const match(theMap, expr, !caseSensitive);
449 if (!match.validRE())
452 // Search the vector of 'keys' from 'start' for one that matches the
453 // predicate 'match'. Searching can be forward or backward from start.
455 return std::find_if(start, keys.end(), match);
457 vector<string>::const_reverse_iterator rit(start);
458 vector<string>::const_reverse_iterator rend = keys.rend();
459 rit = std::find_if(rit, rend, match);
463 // This is correct and always safe.
464 // (See Meyer's Effective STL, Item 28.)
465 return (++rit).base();
469 string const parseBibTeX(string data, string const & findkey)
472 // at first we delete all characters right of '%' and
473 // replace tabs through a space and remove leading spaces
474 // we read the data line by line so that the \n are
478 string dummy = token(data,'\n', Entries);
479 while (!dummy.empty()) {
480 dummy = subst(dummy, '\t', ' '); // no tabs
481 dummy = ltrim(dummy); // no leading spaces
482 // ignore lines with a beginning '%' or ignore all right of %
483 string::size_type const idx =
484 dummy.empty() ? string::npos : dummy.find('%');
485 if (idx != string::npos)
486 // Check if this is really a comment or just "\%"
487 if (idx == 0 || dummy[idx - 1] != '\\')
488 dummy.erase(idx, string::npos);
489 else // This is "\%", so just erase the '\'
490 dummy.erase(idx - 1, 1);
491 // do we have a new token or a new line of
492 // the same one? In the first case we ignore
493 // the \n and in the second we replace it
495 if (!dummy.empty()) {
496 if (!contains(dummy, '='))
497 data_ += ' ' + dummy;
501 dummy = token(data, '\n', ++Entries);
504 // replace double commas with "" for easy scanning
505 data = subst(data_, ",,", "\"\"");
511 // now get only the important line of the bibtex entry.
512 // all entries are devided by ',' except the last one.
513 data += ','; // now we have same behaviour for all entries
514 // because the last one is "blah ... }"
517 // parsing of title and booktitle is different from the
518 // others, because booktitle contains title
520 dummy = token(data, ',', Entries++);
521 if (!dummy.empty()) {
522 found = contains(ascii_lowercase(dummy), findkey);
523 if (findkey == "title" &&
524 contains(ascii_lowercase(dummy), "booktitle"))
527 } while (!found && !dummy.empty());
532 // we are not sure, if we get all, because "key= "blah, blah" is
534 // Therefore we read all until the next "=" character, which follows a
537 dummy = token(data, ',', Entries++);
538 while (!contains(dummy, '=') && !dummy.empty()) {
539 keyvalue += ',' + dummy;
540 dummy = token(data, ',', Entries++);
543 // replace double "" with originals ,, (two commas)
544 // leaving us with the all-important line
545 data = subst(keyvalue, "\"\"", ",,");
550 // 2. if there is no opening '{' then a closing '{' is probably cruft.
551 if (!contains(data, '{'))
552 data = rtrim(data, "}");
553 // happens, when last keyword
554 string::size_type const idx =
555 !data.empty() ? data.find('=') : string::npos;
557 if (idx == string::npos)
560 data = trim(data.substr(idx));
562 if (data.length() < 2 || data[0] != '=') { // a valid entry?
565 // delete '=' and the following spaces
566 data = ltrim(data, " =");
567 if (data.length() < 2) {
568 return data; // not long enough to find delimiters
570 string::size_type keypos = 1;
572 if (data[0] == '{') {
574 } else if (data[0] == '"') {
577 // no {} and no "", pure data but with a
578 // possible ',' at the end
579 return rtrim(data, ",");
581 string tmp = data.substr(keypos);
582 while (tmp.find('{') != string::npos &&
583 tmp.find('}') != string::npos &&
584 tmp.find('{') < tmp.find('}') &&
585 tmp.find('{') < tmp.find(enclosing)) {
587 keypos += tmp.find('{') + 1;
588 tmp = data.substr(keypos);
589 keypos += tmp.find('}') + 1;
590 tmp = data.substr(keypos);
592 if (tmp.find(enclosing) == string::npos)
595 keypos += tmp.find(enclosing);
596 return data.substr(1, keypos - 1);
606 char const * const citeCommands[] = {
607 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
608 "citeyear", "citeyearpar" };
610 unsigned int const nCiteCommands =
611 sizeof(citeCommands) / sizeof(char *);
613 CiteStyle const citeStyles[] = {
614 CITE, CITET, CITEP, CITEALT, CITEALP,
615 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
617 unsigned int const nCiteStyles =
618 sizeof(citeStyles) / sizeof(CiteStyle);
620 CiteStyle const citeStylesFull[] = {
621 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
623 unsigned int const nCiteStylesFull =
624 sizeof(citeStylesFull) / sizeof(CiteStyle);
626 CiteStyle const citeStylesUCase[] = {
627 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
629 unsigned int const nCiteStylesUCase =
630 sizeof(citeStylesUCase) / sizeof(CiteStyle);
635 CitationStyle::CitationStyle(string const & command)
636 : style(CITE), full(false), forceUCase(false)
641 string cmd = command;
647 string::size_type const n = cmd.size() - 1;
648 if (cmd != "cite" && cmd[n] == '*') {
650 cmd = cmd.substr(0,n);
653 char const * const * const last = citeCommands + nCiteCommands;
654 char const * const * const ptr = std::find(citeCommands, last, cmd);
657 size_t idx = ptr - citeCommands;
658 style = citeStyles[idx];
663 string const CitationStyle::asLatexStr() const
665 string cite = citeCommands[style];
667 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
668 if (std::find(citeStylesFull, last, style) != last)
673 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
674 if (std::find(citeStylesUCase, last, style) != last)
682 CiteEngine_enum getEngine(Buffer const & buffer)
684 return buffer.params().cite_engine;
688 vector<CiteStyle> const getCiteStyles(CiteEngine_enum const & engine)
690 unsigned int nStyles = 0;
691 unsigned int start = 0;
698 case ENGINE_NATBIB_AUTHORYEAR:
699 case ENGINE_NATBIB_NUMERICAL:
700 nStyles = nCiteStyles - 1;
704 nStyles = nCiteStyles;
709 typedef vector<CiteStyle> cite_vec;
711 cite_vec styles(nStyles);
712 cite_vec::size_type i = 0;
714 for (; i != styles.size(); ++i, ++j)
715 styles[i] = citeStyles[j];
722 getNumericalStrings(string const & key,
723 InfoMap const & map, vector<CiteStyle> const & styles)
726 return vector<string>();
729 string const author = getAbbreviatedAuthor(map, key);
730 string const year = getYear(map, key);
731 if (author.empty() || year.empty())
732 return vector<string>();
734 vector<string> vec(styles.size());
735 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
745 str = author + " [#ID]";
749 str = author + " #ID";
765 str = '(' + year + ')';
777 getAuthorYearStrings(string const & key,
778 InfoMap const & map, vector<CiteStyle> const & styles)
781 return vector<string>();
784 string const author = getAbbreviatedAuthor(map, key);
785 string const year = getYear(map, key);
786 if (author.empty() || year.empty())
787 return vector<string>();
789 vector<string> vec(styles.size());
790 for (vector<string>::size_type i = 0; i != vec.size(); ++i) {
795 // jurabib only: Author/Annotator
796 // (i.e. the "before" field, 2nd opt arg)
797 str = author + "/<" + _("before") + '>';
801 str = author + " (" + year + ')';
805 str = '(' + author + ", " + year + ')';
809 str = author + ' ' + year ;
813 str = author + ", " + year ;
825 str = '(' + year + ')';
835 } // namespace biblio