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"
18 #include "BufferParams.h"
20 #include "DispatchResult.h"
21 #include "FuncRequest.h"
22 #include "LaTeXFeatures.h"
24 #include "frontends/controllers/frontend_helpers.h"
26 #include "support/fs_extras.h"
27 #include "support/lstrings.h"
31 #include <boost/filesystem/operations.hpp>
32 #include <boost/filesystem/exception.hpp>
37 using support::ascii_lowercase;
38 using support::contains;
39 using support::FileName;
40 using support::getStringFromVector;
41 using support::getVectorFromString;
43 using support::prefixIs;
46 using support::tokenPos;
55 namespace fs = boost::filesystem;
60 vector<string> const init_possible_cite_commands()
62 char const * const pos[] = {
63 "cite", "citet", "citep", "citealt", "citealp",
64 "citeauthor", "citeyear", "citeyearpar",
65 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
66 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
67 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
69 "footcite", "footcitet", "footcitep", "footcitealt",
70 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
71 "citefield", "citetitle", "cite*"
73 size_t const size_pos = sizeof(pos) / sizeof(pos[0]);
75 return vector<string>(pos, pos + size_pos);
79 vector<string> const & possible_cite_commands()
81 static vector<string> const pos = init_possible_cite_commands();
86 bool is_possible_cite_command(string const & input)
88 vector<string> const & possibles = possible_cite_commands();
89 vector<string>::const_iterator const end = possibles.end();
90 return std::find(possibles.begin(), end, input) != end;
94 string const default_cite_command(biblio::CiteEngine engine)
98 case biblio::ENGINE_BASIC:
101 case biblio::ENGINE_NATBIB_AUTHORYEAR:
104 case biblio::ENGINE_NATBIB_NUMERICAL:
107 case biblio::ENGINE_JURABIB:
116 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
118 string const default_str = default_cite_command(engine);
119 if (!is_possible_cite_command(input))
124 case biblio::ENGINE_BASIC:
125 output = default_str;
128 case biblio::ENGINE_NATBIB_AUTHORYEAR:
129 case biblio::ENGINE_NATBIB_NUMERICAL:
130 if (input == "cite" || input == "citefield" ||
131 input == "citetitle" || input == "cite*")
132 output = default_str;
133 else if (prefixIs(input, "foot"))
134 output = input.substr(4);
139 case biblio::ENGINE_JURABIB: {
140 // Jurabib does not support the 'uppercase' natbib style.
142 output = string(1, 'c') + input.substr(1);
146 // Jurabib does not support the 'full' natbib style.
147 string::size_type const n = output.size() - 1;
148 if (output != "cite*" && output[n] == '*')
149 output = output.substr(0, n);
159 docstring const getNatbibLabel(Buffer const & buffer,
160 string const & citeType, docstring const & keyList,
161 docstring const & before, docstring const & after,
162 biblio::CiteEngine engine)
164 // Only start the process off after the buffer is loaded from file.
165 if (!buffer.fully_loaded())
169 typedef std::map<Buffer const *, BiblioInfo> CachedMap;
170 static CachedMap cached_keys;
172 // and cache the timestamp of the bibliography files.
173 static std::map<FileName, time_t> bibfileStatus;
177 vector<FileName> const & bibfilesCache = buffer.getBibfilesCache();
178 // compare the cached timestamps with the actual ones.
179 bool changed = false;
180 for (vector<FileName>::const_iterator it = bibfilesCache.begin();
181 it != bibfilesCache.end(); ++ it) {
182 FileName const f = *it;
184 std::time_t lastw = fs::last_write_time(f.toFilesystemEncoding());
185 if (lastw != bibfileStatus[f]) {
187 bibfileStatus[f] = lastw;
190 catch (fs::filesystem_error & fserr) {
192 lyxerr << "Couldn't find or read bibtex file "
194 LYXERR(Debug::DEBUG) << "Fs error: "
195 << fserr.what() << endl;
199 // build the list only if the bibfiles have been changed
200 if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
201 biblist.fillWithBibKeys(&buffer);
202 cached_keys[&buffer] = biblist;
204 // use the cached keys
205 biblist = cached_keys[&buffer];
210 // the natbib citation-styles
211 // CITET: author (year)
212 // CITEP: (author,year)
213 // CITEALT: author year
214 // CITEALP: author, year
215 // CITEAUTHOR: author
217 // CITEYEARPAR: (year)
218 // jurabib supports these plus
219 // CITE: author/<before field>
221 // We don't currently use the full or forceUCase fields.
222 string cite_type = asValidLatexCommand(citeType, engine);
223 if (cite_type[0] == 'C')
224 //If we were going to use them, this would mean ForceUCase
225 cite_type = string(1, 'c') + cite_type.substr(1);
226 if (cite_type[cite_type.size() - 1] == '*')
227 //and this would mean FULL
228 cite_type = cite_type.substr(0, cite_type.size() - 1);
230 docstring before_str;
231 if (!before.empty()) {
232 // In CITET and CITEALT mode, the "before" string is
233 // attached to the label associated with each and every key.
234 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
235 // to the front of the whole only.
236 // In other modes, it is not used at all.
237 if (cite_type == "citet" ||
238 cite_type == "citealt" ||
239 cite_type == "citep" ||
240 cite_type == "citealp" ||
241 cite_type == "citeyearpar")
242 before_str = before + ' ';
243 // In CITE (jurabib), the "before" string is used to attach
244 // the annotator (of legal texts) to the author(s) of the
246 else if (cite_type == "cite")
247 before_str = '/' + before;
251 if (!after.empty()) {
252 // The "after" key is appended only to the end of the whole.
253 after_str = ", " + after;
256 // One day, these might be tunable (as they are in BibTeX).
257 char const op = '('; // opening parenthesis.
258 char const cp = ')'; // closing parenthesis.
259 // puctuation mark separating citation entries.
260 char const * const sep = ";";
262 docstring const op_str(' ' + docstring(1, op));
263 docstring const cp_str(docstring(1, cp) + ' ');
264 docstring const sep_str(from_ascii(sep) + ' ');
267 vector<docstring> keys = getVectorFromString(keyList);
268 vector<docstring>::const_iterator it = keys.begin();
269 vector<docstring>::const_iterator end = keys.end();
270 for (; it != end; ++it) {
271 // get the bibdata corresponding to the key
272 docstring const author(biblist.getAbbreviatedAuthor(*it));
273 docstring const year(biblist.getYear(*it));
275 // Something isn't right. Fail safely.
276 if (author.empty() || year.empty())
279 // authors1/<before>; ... ;
280 // authors_last, <after>
281 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
282 if (it == keys.begin())
283 label += author + before_str + sep_str;
285 label += author + sep_str;
287 // (authors1 (<before> year); ... ;
288 // authors_last (<before> year, <after>)
289 } else if (cite_type == "citet") {
291 case biblio::ENGINE_NATBIB_AUTHORYEAR:
292 label += author + op_str + before_str +
295 case biblio::ENGINE_NATBIB_NUMERICAL:
296 label += author + op_str + before_str + '#' + *it + cp + sep_str;
298 case biblio::ENGINE_JURABIB:
299 label += before_str + author + op_str +
302 case biblio::ENGINE_BASIC:
306 // author, year; author, year; ...
307 } else if (cite_type == "citep" ||
308 cite_type == "citealp") {
309 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
310 label += *it + sep_str;
312 label += author + ", " + year + sep_str;
315 // (authors1 <before> year;
316 // authors_last <before> year, <after>)
317 } else if (cite_type == "citealt") {
319 case biblio::ENGINE_NATBIB_AUTHORYEAR:
320 label += author + ' ' + before_str +
323 case biblio::ENGINE_NATBIB_NUMERICAL:
324 label += author + ' ' + before_str + '#' + *it + sep_str;
326 case biblio::ENGINE_JURABIB:
327 label += before_str + author + ' ' +
330 case biblio::ENGINE_BASIC:
334 // author; author; ...
335 } else if (cite_type == "citeauthor") {
336 label += author + sep_str;
339 } else if (cite_type == "citeyear" ||
340 cite_type == "citeyearpar") {
341 label += year + sep_str;
344 label = rtrim(rtrim(label), sep);
346 if (!after_str.empty()) {
347 if (cite_type == "citet") {
348 // insert "after" before last ')'
349 label.insert(label.size() - 1, after_str);
352 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
353 (cite_type == "citeauthor" ||
354 cite_type == "citeyear"));
360 if (!before_str.empty() && (cite_type == "citep" ||
361 cite_type == "citealp" ||
362 cite_type == "citeyearpar")) {
363 label = before_str + label;
366 if (cite_type == "citep" || cite_type == "citeyearpar")
367 label = op + label + cp;
373 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
375 docstring keys(keyList);
378 if (contains(keys, ',')) {
379 // Final comma allows while loop to cover all keys
380 keys = ltrim(split(keys, label, ',')) + ',';
381 while (contains(keys, ',')) {
383 keys = ltrim(split(keys, key, ','));
390 label += ", " + after;
392 return '[' + label + ']';
398 InsetCitation::InsetCitation(InsetCommandParams const & p)
399 : InsetCommand(p, "citation")
403 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
405 docstring const before = getParam("before");
406 docstring const after = getParam("after");
409 biblio::CiteEngine const engine = buffer.params().getEngine();
410 if (engine != biblio::ENGINE_BASIC) {
411 label = getNatbibLabel(buffer, getCmdName(), getParam("key"),
412 before, after, engine);
415 // Fallback to fail-safe
417 label = getBasicLabel(getParam("key"), after);
424 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
426 biblio::CiteEngine const engine = buffer.params().getEngine();
427 if (cache.params == params() && cache.engine == engine)
428 return cache.screen_label;
430 // The label has changed, so we have to re-create it.
431 docstring const glabel = generateLabel(buffer);
433 unsigned int const maxLabelChars = 45;
435 docstring label = glabel;
436 if (label.size() > maxLabelChars) {
437 label.erase(maxLabelChars-3);
441 cache.engine = engine;
442 cache.params = params();
443 cache.generated_label = glabel;
444 cache.screen_label = label;
450 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
451 OutputParams const &) const
455 if (cache.params == params() &&
456 cache.engine == buffer.params().getEngine())
457 str = cache.generated_label;
459 str = generateLabel(buffer);
468 docstring const cleanupWhitespace(docstring const & citelist)
470 docstring::const_iterator it = citelist.begin();
471 docstring::const_iterator end = citelist.end();
472 // Paranoia check: make sure that there is no whitespace in here
473 // -- at least not behind commas or at the beginning
475 char_type last = ',';
476 for (; it != end; ++it) {
479 if (*it != ' ' || last != ',')
485 // end anon namyspace
488 int InsetCitation::docbook(Buffer const &, odocstream & os,
489 OutputParams const &) const
492 << cleanupWhitespace(getParam("key"))
498 int InsetCitation::textString(Buffer const & buf, odocstream & os,
499 OutputParams const & op) const
501 return plaintext(buf, os, op);
505 // Have to overwrite the default InsetCommand method in order to check that
506 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
507 // citations and then changes his mind, turning natbib support off. The output
508 // should revert to \cite[]{}
509 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
510 OutputParams const &) const
512 biblio::CiteEngine cite_engine = buffer.params().getEngine();
514 docstring const cite_str = from_utf8(
515 asValidLatexCommand(getCmdName(), cite_engine));
517 os << "\\" << cite_str;
519 docstring const & before = getParam("before");
520 docstring const & after = getParam("after");
521 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
522 os << '[' << before << "][" << after << ']';
523 else if (!after.empty())
524 os << '[' << after << ']';
526 os << '{' << cleanupWhitespace(getParam("key")) << '}';
532 void InsetCitation::validate(LaTeXFeatures & features) const
534 switch (features.bufferParams().getEngine()) {
535 case biblio::ENGINE_BASIC:
537 case biblio::ENGINE_NATBIB_AUTHORYEAR:
538 case biblio::ENGINE_NATBIB_NUMERICAL:
539 features.require("natbib");
541 case biblio::ENGINE_JURABIB:
542 features.require("jurabib");
548 void InsetCitation::replaceContents(string const & from, string const & to)
550 if (tokenPos(getContents(), ',', from) != -1) {
551 vector<string> items = getVectorFromString(getContents());
552 replace(items.begin(), items.end(), from, to);
553 setContents(getStringFromVector(items));