3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
8 * \author Richard Heck (re-write of BibTeX representation)
10 * Full author contact details are available in file CREDITS.
17 #include "buffer_funcs.h"
19 #include "InsetIterator.h"
20 #include "Paragraph.h"
22 #include "insets/Inset.h"
23 #include "insets/InsetBibitem.h"
24 #include "insets/InsetBibtex.h"
25 #include "insets/InsetInclude.h"
27 #include "support/lstrings.h"
29 #include "boost/regex.hpp"
37 using support::ascii_lowercase;
38 using support::bformat;
39 using support::compare_ascii_no_case;
40 using support::contains;
41 using support::getVectorFromString;
43 using support::prefixIs;
53 BibTeXInfo::BibTeXInfo(): isBibTeX(true)
57 BibTeXInfo::BibTeXInfo(bool isBibTeX): isBibTeX(isBibTeX)
61 bool BibTeXInfo::hasKey(docstring const & key)
63 const_iterator it = find(key);
70 vector<string> const init_possible_cite_commands()
72 char const * const pos[] = {
73 "cite", "citet", "citep", "citealt", "citealp",
74 "citeauthor", "citeyear", "citeyearpar",
75 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
76 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
77 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
79 "footcite", "footcitet", "footcitep", "footcitealt",
80 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
81 "citefield", "citetitle", "cite*"
83 size_t const size_pos = sizeof(pos) / sizeof(pos[0]);
85 return vector<string>(pos, pos + size_pos);
89 vector<string> const & possible_cite_commands()
91 static vector<string> const pos = init_possible_cite_commands();
96 bool is_possible_cite_command(string const & input)
98 vector<string> const & possibles = possible_cite_commands();
99 vector<string>::const_iterator const end = possibles.end();
100 return std::find(possibles.begin(), end, input) != end;
104 string const default_cite_command(CiteEngine engine)
111 case ENGINE_NATBIB_AUTHORYEAR:
114 case ENGINE_NATBIB_NUMERICAL:
128 string const asValidLatexCommand(string const & input,
129 CiteEngine const engine)
131 string const default_str = default_cite_command(engine);
132 if (!is_possible_cite_command(input))
138 output = default_str;
141 case ENGINE_NATBIB_AUTHORYEAR:
142 case ENGINE_NATBIB_NUMERICAL:
143 if (input == "cite" || input == "citefield" ||
144 input == "citetitle" || input == "cite*")
145 output = default_str;
146 else if (prefixIs(input, "foot"))
147 output = input.substr(4);
152 case ENGINE_JURABIB: {
153 // Jurabib does not support the 'uppercase' natbib style.
155 output = string(1, 'c') + input.substr(1);
159 // Jurabib does not support the 'full' natbib style.
160 string::size_type const n = output.size() - 1;
161 if (output != "cite*" && output[n] == '*')
162 output = output.substr(0, n);
172 docstring const familyName(docstring const & name)
177 // Very simple parser
178 docstring fname = name;
180 // possible authorname combinations are:
181 // "Surname, FirstName"
183 // "FirstName Surname"
185 docstring::size_type idx = fname.find(',');
186 if (idx != docstring::npos)
187 return ltrim(fname.substr(0, idx));
188 idx = fname.rfind('.');
189 if (idx != docstring::npos && idx + 1 < fname.size())
190 fname = ltrim(fname.substr(idx + 1));
191 // test if we have a LaTeX Space in front
192 if (fname[0] == '\\')
193 return fname.substr(2);
199 docstring const getAbbreviatedAuthor(BibKeyList const & map, string const & key)
201 BOOST_ASSERT(!map.empty());
202 BibKeyList::const_iterator it = map.find(key);
205 BibTeXInfo const & data = it->second;
210 docstring author = getValueForKey(data, "author");
212 if (author.empty()) {
213 author = getValueForKey(data, "editor");
214 if (author.empty()) {
215 author = getValueForKey(data, "key");
218 return from_utf8(key);
220 return author; //this is the key
224 //OK, we've got some names. Let's format them.
225 //try to split the author list on " and "
226 vector<docstring> const authors = getVectorFromString(author, from_ascii(" and "));
228 if (authors.size() == 2)
229 return bformat(_("%1$s and %2$s"),
230 familyName(authors[0]), familyName(authors[1]));
231 else if (authors.size() > 2)
232 return bformat(_("%1$s et al."), familyName(authors[0]));
234 return familyName(authors[0]);
238 docstring const getYear(BibKeyList const & map, string const & key)
240 BOOST_ASSERT(!map.empty());
242 BibKeyList::const_iterator it = map.find(key);
245 BibTeXInfo const & data = it->second;
250 docstring year = getValueForKey(data, "year");
259 // A functor for use with std::sort, leading to case insensitive sorting
260 class compareNoCase: public std::binary_function<string, string, bool>
263 bool operator()(string const & s1, string const & s2) const {
264 return compare_ascii_no_case(s1, s2) < 0;
270 vector<string> const getKeys(BibKeyList const & map)
272 vector<string> bibkeys;
273 BibKeyList::const_iterator it = map.begin();
274 BibKeyList::const_iterator end = map.end();
275 for (; it != end; ++it) {
276 bibkeys.push_back(it->first);
279 std::sort(bibkeys.begin(), bibkeys.end(), compareNoCase());
284 docstring const getInfo(BibKeyList const & map, string const & key)
286 BOOST_ASSERT(!map.empty());
288 BibKeyList::const_iterator it = map.find(key);
291 BibTeXInfo const & data = it->second;
293 if (!data.isBibTeX) {
294 BibTeXInfo::const_iterator it3 = data.find(from_ascii("ref"));
299 //This could be made alot better using the biblio::TheEntryType
300 //field to customize the output based upon entry type.
302 //Search for all possible "required" fields
303 docstring author = getValueForKey(data, "author");
305 author = getValueForKey(data, "editor");
307 docstring year = getValueForKey(data, "year");
308 docstring title = getValueForKey(data, "title");
309 docstring docLoc = getValueForKey(data, "pages");
310 if (docLoc.empty()) {
311 docLoc = getValueForKey(data, "chapter");
313 docLoc = from_ascii("Ch. ") + docLoc;
315 docLoc = from_ascii("pp. ") + docLoc;
316 docstring media = getValueForKey(data, "journal");
318 media = getValueForKey(data, "publisher");
320 media = getValueForKey(data, "school");
322 media = getValueForKey(data, "institution");
325 docstring volume = getValueForKey(data, "volume");
327 odocstringstream result;
329 result << author << ", ";
333 result << ", " << media;
335 result << ", " << year;
337 result << ", " << docLoc;
339 docstring const result_str = rtrim(result.str());
340 if (!result_str.empty())
343 // This should never happen (or at least be very unusual!)
350 // Escape special chars.
351 // All characters are literals except: '.|*?+(){}[]^$\'
352 // These characters are literals when preceded by a "\", which is done here
353 // @todo: This function should be moved to support, and then the test in tests
354 // should be moved there as well.
355 string const escape_special_chars(string const & expr)
357 // Search for all chars '.|*?+(){}[^$]\'
358 // Note that '[' and '\' must be escaped.
359 // This is a limitation of boost::regex, but all other chars in BREs
360 // are assumed literal.
361 boost::regex reg("[].|*?+(){}^$\\[\\\\]");
363 // $& is a perl-like expression that expands to all
364 // of the current match
365 // The '$' must be prefixed with the escape character '\' for
366 // boost to treat it as a literal.
367 // Thus, to prefix a matched expression with '\', we use:
368 return boost::regex_replace(expr, reg, "\\\\$&");
372 // A functor for use with std::find_if, used to ascertain whether a
373 // data entry matches the required regex_
374 // @throws: boost::regex_error if the supplied regex pattern is not valid
375 // @todo: This function should be moved to support.
376 class RegexMatch : public std::unary_function<string, bool>
379 // re and icase are used to construct an instance of boost::RegEx.
380 // if icase is true, then matching is insensitive to case
381 RegexMatch(BibKeyList const & m, string const & re, bool icase)
382 : map_(m), regex_(re, icase) {}
384 bool operator()(string const & key) const {
385 //FIXME This should search the monolith.
386 BibKeyList::const_iterator info = map_.find(key);
387 if (info == map_.end())
390 BibTeXInfo const kvm = info->second;
391 string const data = key + ' ' + to_utf8(kvm.allData);
393 return boost::regex_search(data, regex_);
396 BibKeyList const map_;
397 mutable boost::regex regex_;
403 vector<string>::const_iterator searchKeys(BibKeyList const & theMap,
404 vector<string> const & keys,
405 string const & search_expr,
406 vector<string>::const_iterator start,
407 Search type, Direction dir, bool caseSensitive)
409 // Preliminary checks
410 if (start < keys.begin() || start >= keys.end())
413 string expr = trim(search_expr);
418 // We must escape special chars in the search_expr so that
419 // it is treated as a simple string by boost::regex.
420 expr = escape_special_chars(expr);
423 // Build the functor that will be passed to find_if.
424 RegexMatch const match(theMap, expr, !caseSensitive);
426 // Search the vector of 'keys' from 'start' for one
427 // that matches the predicate 'match'. Searching can
428 // be forward or backward from start.
430 return std::find_if(start, keys.end(), match);
432 vector<string>::const_reverse_iterator rit(start);
433 vector<string>::const_reverse_iterator rend = keys.rend();
434 rit = std::find_if(rit, rend, match);
438 // This is correct and always safe.
439 // (See Meyer's Effective STL, Item 28.)
440 return (++rit).base();
442 catch (boost::regex_error &) {
448 docstring const getValueForKey(BibTeXInfo const & data, string const & findkey)
450 docstring key = from_ascii(findkey);
451 BibTeXInfo::const_iterator it = data.find(key);
452 if (it == data.end())
454 //FIXME ?? return it->second??
455 BibTeXInfo & data2 = const_cast<BibTeXInfo &>(data);
462 char const * const citeCommands[] = {
463 "cite", "citet", "citep", "citealt", "citealp", "citeauthor",
464 "citeyear", "citeyearpar" };
466 unsigned int const nCiteCommands =
467 sizeof(citeCommands) / sizeof(char *);
469 CiteStyle const citeStyles[] = {
470 CITE, CITET, CITEP, CITEALT, CITEALP,
471 CITEAUTHOR, CITEYEAR, CITEYEARPAR };
473 unsigned int const nCiteStyles =
474 sizeof(citeStyles) / sizeof(CiteStyle);
476 CiteStyle const citeStylesFull[] = {
477 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
479 unsigned int const nCiteStylesFull =
480 sizeof(citeStylesFull) / sizeof(CiteStyle);
482 CiteStyle const citeStylesUCase[] = {
483 CITET, CITEP, CITEALT, CITEALP, CITEAUTHOR };
485 unsigned int const nCiteStylesUCase =
486 sizeof(citeStylesUCase) / sizeof(CiteStyle);
491 CitationStyle::CitationStyle(string const & command)
492 : style(CITE), full(false), forceUCase(false)
497 string cmd = command;
503 string::size_type const n = cmd.size() - 1;
504 if (cmd != "cite" && cmd[n] == '*') {
506 cmd = cmd.substr(0,n);
509 char const * const * const last = citeCommands + nCiteCommands;
510 char const * const * const ptr = std::find(citeCommands, last, cmd);
513 size_t idx = ptr - citeCommands;
514 style = citeStyles[idx];
519 string const CitationStyle::asLatexStr() const
521 string cite = citeCommands[style];
523 CiteStyle const * last = citeStylesFull + nCiteStylesFull;
524 if (std::find(citeStylesFull, last, style) != last)
529 CiteStyle const * last = citeStylesUCase + nCiteStylesUCase;
530 if (std::find(citeStylesUCase, last, style) != last)
538 vector<CiteStyle> const getCiteStyles(CiteEngine const engine)
540 unsigned int nStyles = 0;
541 unsigned int start = 0;
548 case ENGINE_NATBIB_AUTHORYEAR:
549 case ENGINE_NATBIB_NUMERICAL:
550 nStyles = nCiteStyles - 1;
554 nStyles = nCiteStyles;
559 typedef vector<CiteStyle> cite_vec;
561 cite_vec styles(nStyles);
562 cite_vec::size_type i = 0;
564 for (; i != styles.size(); ++i, ++j)
565 styles[i] = citeStyles[j];
571 vector<docstring> const
572 getNumericalStrings(string const & key,
573 BibKeyList const & map, vector<CiteStyle> const & styles)
576 return vector<docstring>();
578 docstring const author = getAbbreviatedAuthor(map, key);
579 docstring const year = getYear(map, key);
580 if (author.empty() || year.empty())
581 return vector<docstring>();
583 vector<docstring> vec(styles.size());
584 for (vector<docstring>::size_type i = 0; i != vec.size(); ++i) {
590 str = from_ascii("[#ID]");
594 str = author + " [#ID]";
598 str = author + " #ID";
602 str = from_ascii("#ID");
614 str = '(' + year + ')';
625 vector<docstring> const
626 getAuthorYearStrings(string const & key,
627 BibKeyList const & map, vector<CiteStyle> const & styles)
630 return vector<docstring>();
632 docstring const author = getAbbreviatedAuthor(map, key);
633 docstring const year = getYear(map, key);
634 if (author.empty() || year.empty())
635 return vector<docstring>();
637 vector<docstring> vec(styles.size());
638 for (vector<docstring>::size_type i = 0; i != vec.size(); ++i) {
643 // jurabib only: Author/Annotator
644 // (i.e. the "before" field, 2nd opt arg)
645 str = author + "/<" + _("before") + '>';
649 str = author + " (" + year + ')';
653 str = '(' + author + ", " + year + ')';
657 str = author + ' ' + year ;
661 str = author + ", " + year ;
673 str = '(' + year + ')';
684 void fillWithBibKeys(Buffer const * const buf,
687 /// if this is a child document and the parent is already loaded
688 /// use the parent's list instead [ale990412]
689 Buffer const * const tmp = buf->getMasterBuffer();
692 fillWithBibKeys(tmp, keys);
696 // Pre-load all child documents.
697 loadChildDocuments(*buf);
699 for (InsetIterator it = inset_iterator_begin(buf->inset()); it; ++it)
700 it->fillWithBibKeys(*buf, keys, it);
702 } // namespace biblio