2 * \file InsetCitation.cpp
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 "InsetCitation.h"
17 #include "BufferParams.h"
19 #include "DispatchResult.h"
20 #include "FuncRequest.h"
21 #include "LaTeXFeatures.h"
23 #include "support/fs_extras.h"
24 #include "support/lstrings.h"
28 #include <boost/filesystem/operations.hpp>
29 #include <boost/filesystem/exception.hpp>
34 using support::FileName;
35 using support::getStringFromVector;
36 using support::getVectorFromString;
38 using support::prefixIs;
41 using support::tokenPos;
47 namespace fs = boost::filesystem;
52 vector<string> const init_possible_cite_commands()
54 char const * const possible[] = {
55 "cite", "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", "footciteyearpar",
63 "citefield", "citetitle", "cite*"
65 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
67 return vector<string>(possible, possible + size_possible);
71 vector<string> const & possible_cite_commands()
73 static vector<string> const possible = init_possible_cite_commands();
78 bool is_possible_cite_command(string const & input)
80 vector<string> const & possibles = possible_cite_commands();
81 vector<string>::const_iterator const end = possibles.end();
82 return std::find(possibles.begin(), end, input) != end;
86 string const default_cite_command(biblio::CiteEngine engine)
90 case biblio::ENGINE_BASIC:
93 case biblio::ENGINE_NATBIB_AUTHORYEAR:
96 case biblio::ENGINE_NATBIB_NUMERICAL:
99 case biblio::ENGINE_JURABIB:
108 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
110 string const default_str = default_cite_command(engine);
111 if (!is_possible_cite_command(input))
116 case biblio::ENGINE_BASIC:
117 output = default_str;
120 case biblio::ENGINE_NATBIB_AUTHORYEAR:
121 case biblio::ENGINE_NATBIB_NUMERICAL:
122 if (input == "cite" || input == "citefield" ||
123 input == "citetitle" || input == "cite*")
124 output = default_str;
125 else if (prefixIs(input, "foot"))
126 output = input.substr(4);
131 case biblio::ENGINE_JURABIB: {
132 // Jurabib does not support the 'uppercase' natbib style.
134 output = string(1, 'c') + input.substr(1);
138 // Jurabib does not support the 'full' natbib style.
139 string::size_type const n = output.size() - 1;
140 if (output != "cite*" && output[n] == '*')
141 output = output.substr(0, n);
151 docstring const getNatbibLabel(Buffer const & buffer,
152 string const & citeType, docstring const & keyList,
153 docstring const & before, docstring const & after,
154 biblio::CiteEngine engine)
156 // Only start the process off after the buffer is loaded from file.
157 if (!buffer.fully_loaded())
161 typedef std::map<Buffer const *, BiblioInfo> CachedMap;
162 static CachedMap cached_keys;
164 // and cache the timestamp of the bibliography files.
165 static std::map<FileName, time_t> bibfileStatus;
169 vector<FileName> const & bibfilesCache = buffer.getBibfilesCache();
170 // compare the cached timestamps with the actual ones.
171 bool changed = false;
172 for (vector<FileName>::const_iterator it = bibfilesCache.begin();
173 it != bibfilesCache.end(); ++ it) {
174 FileName const f = *it;
176 std::time_t lastw = fs::last_write_time(f.toFilesystemEncoding());
177 if (lastw != bibfileStatus[f]) {
179 bibfileStatus[f] = lastw;
182 catch (fs::filesystem_error & fserr) {
184 lyxerr << "Couldn't find or read bibtex file "
186 LYXERR(Debug::DEBUG) << "Fs error: "
187 << fserr.what() << endl;
191 // build the list only if the bibfiles have been changed
192 if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
193 biblist.fillWithBibKeys(&buffer);
194 cached_keys[&buffer] = biblist;
196 // use the cached keys
197 biblist = cached_keys[&buffer];
202 // the natbib citation-styles
203 // CITET: author (year)
204 // CITEP: (author,year)
205 // CITEALT: author year
206 // CITEALP: author, year
207 // CITEAUTHOR: author
209 // CITEYEARPAR: (year)
210 // jurabib supports these plus
211 // CITE: author/<before field>
213 // We don't currently use the full or forceUCase fields.
214 string cite_type = asValidLatexCommand(citeType, engine);
215 if (cite_type[0] == 'C')
216 //If we were going to use them, this would mean ForceUCase
217 cite_type = string(1, 'c') + cite_type.substr(1);
218 if (cite_type[cite_type.size() - 1] == '*')
219 //and this would mean FULL
220 cite_type = cite_type.substr(0, cite_type.size() - 1);
222 docstring before_str;
223 if (!before.empty()) {
224 // In CITET and CITEALT mode, the "before" string is
225 // attached to the label associated with each and every key.
226 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
227 // to the front of the whole only.
228 // In other modes, it is not used at all.
229 if (cite_type == "citet" ||
230 cite_type == "citealt" ||
231 cite_type == "citep" ||
232 cite_type == "citealp" ||
233 cite_type == "citeyearpar")
234 before_str = before + ' ';
235 // In CITE (jurabib), the "before" string is used to attach
236 // the annotator (of legal texts) to the author(s) of the
238 else if (cite_type == "cite")
239 before_str = '/' + before;
243 if (!after.empty()) {
244 // The "after" key is appended only to the end of the whole.
245 after_str = ", " + after;
248 // One day, these might be tunable (as they are in BibTeX).
249 char const op = '('; // opening parenthesis.
250 char const cp = ')'; // closing parenthesis.
251 // puctuation mark separating citation entries.
252 char const * const sep = ";";
254 docstring const op_str(' ' + docstring(1, op));
255 docstring const cp_str(docstring(1, cp) + ' ');
256 docstring const sep_str(from_ascii(sep) + ' ');
259 vector<docstring> keys = getVectorFromString(keyList);
260 vector<docstring>::const_iterator it = keys.begin();
261 vector<docstring>::const_iterator end = keys.end();
262 for (; it != end; ++it) {
263 // get the bibdata corresponding to the key
264 docstring const author(biblist.getAbbreviatedAuthor(*it));
265 docstring const year(biblist.getYear(*it));
267 // Something isn't right. Fail safely.
268 if (author.empty() || year.empty())
271 // authors1/<before>; ... ;
272 // authors_last, <after>
273 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
274 if (it == keys.begin())
275 label += author + before_str + sep_str;
277 label += author + sep_str;
279 // (authors1 (<before> year); ... ;
280 // authors_last (<before> year, <after>)
281 } else if (cite_type == "citet") {
283 case biblio::ENGINE_NATBIB_AUTHORYEAR:
284 label += author + op_str + before_str +
287 case biblio::ENGINE_NATBIB_NUMERICAL:
288 label += author + op_str + before_str + '#' + *it + cp + sep_str;
290 case biblio::ENGINE_JURABIB:
291 label += before_str + author + op_str +
294 case biblio::ENGINE_BASIC:
298 // author, year; author, year; ...
299 } else if (cite_type == "citep" ||
300 cite_type == "citealp") {
301 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
302 label += *it + sep_str;
304 label += author + ", " + year + sep_str;
307 // (authors1 <before> year;
308 // authors_last <before> year, <after>)
309 } else if (cite_type == "citealt") {
311 case biblio::ENGINE_NATBIB_AUTHORYEAR:
312 label += author + ' ' + before_str +
315 case biblio::ENGINE_NATBIB_NUMERICAL:
316 label += author + ' ' + before_str + '#' + *it + sep_str;
318 case biblio::ENGINE_JURABIB:
319 label += before_str + author + ' ' +
322 case biblio::ENGINE_BASIC:
326 // author; author; ...
327 } else if (cite_type == "citeauthor") {
328 label += author + sep_str;
331 } else if (cite_type == "citeyear" ||
332 cite_type == "citeyearpar") {
333 label += year + sep_str;
336 label = rtrim(rtrim(label), sep);
338 if (!after_str.empty()) {
339 if (cite_type == "citet") {
340 // insert "after" before last ')'
341 label.insert(label.size() - 1, after_str);
344 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
345 (cite_type == "citeauthor" ||
346 cite_type == "citeyear"));
352 if (!before_str.empty() && (cite_type == "citep" ||
353 cite_type == "citealp" ||
354 cite_type == "citeyearpar")) {
355 label = before_str + label;
358 if (cite_type == "citep" || cite_type == "citeyearpar")
359 label = op + label + cp;
365 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
367 using support::contains;
369 docstring keys(keyList);
372 if (contains(keys, ',')) {
373 // Final comma allows while loop to cover all keys
374 keys = ltrim(split(keys, label, ',')) + ',';
375 while (contains(keys, ',')) {
377 keys = ltrim(split(keys, key, ','));
384 label += ", " + after;
386 return '[' + label + ']';
392 InsetCitation::InsetCitation(InsetCommandParams const & p)
393 : InsetCommand(p, "citation")
397 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
399 docstring const before = getParam("before");
400 docstring const after = getParam("after");
403 biblio::CiteEngine const engine = buffer.params().getEngine();
404 if (engine != biblio::ENGINE_BASIC) {
405 label = getNatbibLabel(buffer, getCmdName(), getParam("key"),
406 before, after, engine);
409 // Fallback to fail-safe
411 label = getBasicLabel(getParam("key"), after);
418 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
420 biblio::CiteEngine const engine = buffer.params().getEngine();
421 if (cache.params == params() && cache.engine == engine)
422 return cache.screen_label;
424 // The label has changed, so we have to re-create it.
425 docstring const glabel = generateLabel(buffer);
427 unsigned int const maxLabelChars = 45;
429 docstring label = glabel;
430 if (label.size() > maxLabelChars) {
431 label.erase(maxLabelChars-3);
435 cache.engine = engine;
436 cache.params = params();
437 cache.generated_label = glabel;
438 cache.screen_label = label;
444 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
445 OutputParams const &) const
449 if (cache.params == params() &&
450 cache.engine == buffer.params().getEngine())
451 str = cache.generated_label;
453 str = generateLabel(buffer);
460 static docstring const cleanupWhitespace(docstring const & citelist)
462 docstring::const_iterator it = citelist.begin();
463 docstring::const_iterator end = citelist.end();
464 // Paranoia check: make sure that there is no whitespace in here
465 // -- at least not behind commas or at the beginning
467 char_type last = ',';
468 for (; it != end; ++it) {
471 if (*it != ' ' || last != ',')
478 int InsetCitation::docbook(Buffer const &, odocstream & os,
479 OutputParams const &) const
482 << cleanupWhitespace(getParam("key"))
488 int InsetCitation::textString(Buffer const & buf, odocstream & os,
489 OutputParams const & op) const
491 return plaintext(buf, os, op);
495 // Have to overwrite the default InsetCommand method in order to check that
496 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
497 // citations and then changes his mind, turning natbib support off. The output
498 // should revert to \cite[]{}
499 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
500 OutputParams const &) const
502 biblio::CiteEngine cite_engine = buffer.params().getEngine();
504 docstring const cite_str = from_utf8(
505 asValidLatexCommand(getCmdName(), cite_engine));
507 os << "\\" << cite_str;
509 docstring const & before = getParam("before");
510 docstring const & after = getParam("after");
511 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
512 os << '[' << before << "][" << after << ']';
513 else if (!after.empty())
514 os << '[' << after << ']';
516 os << '{' << cleanupWhitespace(getParam("key")) << '}';
522 void InsetCitation::validate(LaTeXFeatures & features) const
524 switch (features.bufferParams().getEngine()) {
525 case biblio::ENGINE_BASIC:
527 case biblio::ENGINE_NATBIB_AUTHORYEAR:
528 case biblio::ENGINE_NATBIB_NUMERICAL:
529 features.require("natbib");
531 case biblio::ENGINE_JURABIB:
532 features.require("jurabib");
538 void InsetCitation::replaceContents(string const & from, string const & to)
540 if (tokenPos(getContents(), ',', from) != -1) {
541 vector<string> items = getVectorFromString(getContents());
542 std::replace(items.begin(), items.end(), from, to);
543 setContents(getStringFromVector(items));