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.
14 #include "insetcite.h"
17 #include "bufferparams.h"
18 #include "BufferView.h"
20 #include "dispatchresult.h"
21 #include "funcrequest.h"
22 #include "LaTeXFeatures.h"
24 #include "frontends/controllers/biblio.h"
26 #include "support/fs_extras.h"
27 #include "support/lstrings.h"
29 #include <boost/filesystem/operations.hpp>
30 #include <boost/filesystem/exception.hpp>
32 using lyx::support::ascii_lowercase;
33 using lyx::support::contains;
34 using lyx::support::getVectorFromString;
35 using lyx::support::ltrim;
36 using lyx::support::rtrim;
37 using lyx::support::split;
45 namespace biblio = lyx::biblio;
46 namespace fs = boost::filesystem;
51 string const getNatbibLabel(Buffer const & buffer,
52 string const & citeType, string const & keyList,
53 string const & before, string const & after,
54 biblio::CiteEngine engine)
56 // Only start the process off after the buffer is loaded from file.
57 if (!buffer.fully_loaded())
61 typedef std::map<Buffer const *, biblio::InfoMap> CachedMap;
62 static CachedMap cached_keys;
64 // and cache the timestamp of the bibliography files.
65 static std::map<string, time_t> bibfileStatus;
67 biblio::InfoMap infomap;
69 vector<string> const & bibfilesCache = buffer.getBibfilesCache();
70 // compare the cached timestamps with the actual ones.
72 for (vector<string>::const_iterator it = bibfilesCache.begin();
73 it != bibfilesCache.end(); ++ it) {
76 std::time_t lastw = fs::last_write_time(f);
77 if (lastw != bibfileStatus[f]) {
79 bibfileStatus[f] = lastw;
82 catch (fs::filesystem_error & fserr) {
84 lyxerr << "Couldn't find or read bibtex file "
86 lyxerr[Debug::DEBUG] << "Fs error: "
87 << fserr.what() << endl;
91 // build the keylist only if the bibfiles have been changed
92 if (cached_keys.empty() || bibfileStatus.empty() || changed) {
93 typedef vector<std::pair<string, string> > InfoType;
95 buffer.fillWithBibKeys(bibkeys);
97 InfoType::const_iterator bit = bibkeys.begin();
98 InfoType::const_iterator bend = bibkeys.end();
100 for (; bit != bend; ++bit)
101 infomap[bit->first] = bit->second;
103 cached_keys[&buffer] = infomap;
105 // use the cached keys
106 infomap = cached_keys[&buffer];
111 // the natbib citation-styles
112 // CITET: author (year)
113 // CITEP: (author,year)
114 // CITEALT: author year
115 // CITEALP: author, year
116 // CITEAUTHOR: author
118 // CITEYEARPAR: (year)
119 // jurabib supports these plus
120 // CITE: author/<before field>
122 // We don't currently use the full or forceUCase fields.
123 string cite_type = biblio::asValidLatexCommand(citeType, engine);
124 if (cite_type[0] == 'C')
125 cite_type = string(1, 'c') + cite_type.substr(1);
126 if (cite_type[cite_type.size() - 1] == '*')
127 cite_type = cite_type.substr(0, cite_type.size() - 1);
130 if (!before.empty()) {
131 // In CITET and CITEALT mode, the "before" string is
132 // attached to the label associated with each and every key.
133 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
134 // to the front of the whole only.
135 // In other modes, it is not used at all.
136 if (cite_type == "citet" ||
137 cite_type == "citealt" ||
138 cite_type == "citep" ||
139 cite_type == "citealp" ||
140 cite_type == "citeyearpar")
141 before_str = before + ' ';
142 // In CITE (jurabib), the "before" string is used to attach
143 // the annotator (of legal texts) to the author(s) of the
145 else if (cite_type == "cite")
146 before_str = '/' + before;
150 if (!after.empty()) {
151 // The "after" key is appended only to the end of the whole.
152 after_str = ", " + after;
155 // One day, these might be tunable (as they are in BibTeX).
156 char const op = '('; // opening parenthesis.
157 char const cp = ')'; // closing parenthesis.
158 // puctuation mark separating citation entries.
159 char const * const sep = ";";
161 string const op_str(' ' + string(1, op));
162 string const cp_str(string(1, cp) + ' ');
163 string const sep_str(string(sep) + ' ');
166 vector<string> keys = getVectorFromString(keyList);
167 vector<string>::const_iterator it = keys.begin();
168 vector<string>::const_iterator end = keys.end();
169 for (; it != end; ++it) {
170 // get the bibdata corresponding to the key
171 string const author(biblio::getAbbreviatedAuthor(infomap, *it));
172 string const year(biblio::getYear(infomap, *it));
174 // Something isn't right. Fail safely.
175 if (author.empty() || year.empty())
178 // authors1/<before>; ... ;
179 // authors_last, <after>
180 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
181 if (it == keys.begin())
182 label += author + before_str + sep_str;
184 label += author + sep_str;
186 // (authors1 (<before> year); ... ;
187 // authors_last (<before> year, <after>)
188 } else if (cite_type == "citet") {
190 case biblio::ENGINE_NATBIB_AUTHORYEAR:
191 label += author + op_str + before_str +
194 case biblio::ENGINE_NATBIB_NUMERICAL:
195 label += author + op_str + before_str +
196 '#' + *it + cp + sep_str;
198 case biblio::ENGINE_JURABIB:
199 label += before_str + author + op_str +
202 case biblio::ENGINE_BASIC:
206 // author, year; author, year; ...
207 } else if (cite_type == "citep" ||
208 cite_type == "citealp") {
209 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
210 label += *it + sep_str;
212 label += author + ", " + year + sep_str;
215 // (authors1 <before> year;
216 // authors_last <before> year, <after>)
217 } else if (cite_type == "citealt") {
219 case biblio::ENGINE_NATBIB_AUTHORYEAR:
220 label += author + ' ' + before_str +
223 case biblio::ENGINE_NATBIB_NUMERICAL:
224 label += author + ' ' + before_str +
227 case biblio::ENGINE_JURABIB:
228 label += before_str + author + ' ' +
231 case biblio::ENGINE_BASIC:
235 // author; author; ...
236 } else if (cite_type == "citeauthor") {
237 label += author + sep_str;
240 } else if (cite_type == "citeyear" ||
241 cite_type == "citeyearpar") {
242 label += year + sep_str;
245 label = rtrim(rtrim(label), sep);
247 if (!after_str.empty()) {
248 if (cite_type == "citet") {
249 // insert "after" before last ')'
250 label.insert(label.size() - 1, after_str);
253 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
254 (cite_type == "citeauthor" ||
255 cite_type == "citeyear"));
261 if (!before_str.empty() && (cite_type == "citep" ||
262 cite_type == "citealp" ||
263 cite_type == "citeyearpar")) {
264 label = before_str + label;
267 if (cite_type == "citep" || cite_type == "citeyearpar")
268 label = string(1, op) + label + string(1, cp);
274 string const getBasicLabel(string const & keyList, string const & after)
276 string keys(keyList);
279 if (contains(keys, ',')) {
280 // Final comma allows while loop to cover all keys
281 keys = ltrim(split(keys, label, ',')) + ',';
282 while (contains(keys, ',')) {
284 keys = ltrim(split(keys, key, ','));
291 label += ", " + after;
293 return '[' + label + ']';
299 InsetCitation::InsetCitation(InsetCommandParams const & p)
300 : InsetCommand(p, "citation")
304 string const InsetCitation::generateLabel(Buffer const & buffer) const
306 string const before = getSecOptions();
307 string const after = getOptions();
310 biblio::CiteEngine const engine = buffer.params().cite_engine;
311 if (engine != biblio::ENGINE_BASIC) {
312 label = getNatbibLabel(buffer, getCmdName(), getContents(),
313 before, after, engine);
316 // Fallback to fail-safe
318 label = getBasicLabel(getContents(), after);
325 string const InsetCitation::getScreenLabel(Buffer const & buffer) const
327 biblio::CiteEngine const engine = biblio::getEngine(buffer);
328 if (cache.params == params() && cache.engine == engine)
329 return cache.screen_label;
331 // The label has changed, so we have to re-create it.
332 string const before = getSecOptions();
333 string const after = getOptions();
335 string const glabel = generateLabel(buffer);
337 unsigned int const maxLabelChars = 45;
339 string label = glabel;
340 if (label.size() > maxLabelChars) {
341 label.erase(maxLabelChars-3);
345 cache.engine = engine;
346 cache.params = params();
347 cache.generated_label = glabel;
348 cache.screen_label = label;
354 int InsetCitation::plaintext(Buffer const & buffer, ostream & os, OutputParams const &) const
356 if (cache.params == params() &&
357 cache.engine == biblio::getEngine(buffer))
358 os << cache.generated_label;
360 os << generateLabel(buffer);
367 string const cleanupWhitespace(string const & citelist)
369 string::const_iterator it = citelist.begin();
370 string::const_iterator end = citelist.end();
371 // Paranoia check: make sure that there is no whitespace in here
372 // -- at least not behind commas or at the beginning
375 for (; it != end; ++it) {
378 if (*it != ' ' || last != ',')
384 // end anon namyspace
387 int InsetCitation::docbook(Buffer const &, ostream & os, OutputParams const &) const
389 os << "<citation>" << cleanupWhitespace(getContents()) << "</citation>";
394 int InsetCitation::textString(Buffer const & buf, ostream & os,
395 OutputParams const & op) const
397 return plaintext(buf, os, op);
401 // Have to overwrite the default InsetCommand method in order to check that
402 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
403 // citations and then changes his mind, turning natbib support off. The output
404 // should revert to \cite[]{}
405 int InsetCitation::latex(Buffer const & buffer, ostream & os,
406 OutputParams const &) const
408 biblio::CiteEngine const cite_engine = buffer.params().cite_engine;
409 string const cite_str =
410 biblio::asValidLatexCommand(getCmdName(), cite_engine);
412 os << "\\" << cite_str;
414 string const before = getSecOptions();
415 string const after = getOptions();
416 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
417 os << '[' << before << "][" << after << ']';
418 else if (!after.empty())
419 os << '[' << after << ']';
421 os << '{' << cleanupWhitespace(getContents()) << '}';
427 void InsetCitation::validate(LaTeXFeatures & features) const
429 switch (features.bufferParams().cite_engine) {
430 case biblio::ENGINE_BASIC:
432 case biblio::ENGINE_NATBIB_AUTHORYEAR:
433 case biblio::ENGINE_NATBIB_NUMERICAL:
434 features.require("natbib");
436 case biblio::ENGINE_JURABIB:
437 features.require("jurabib");