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 "frontends/controllers/frontend_helpers.h"
25 #include "support/fs_extras.h"
26 #include "support/lstrings.h"
30 #include <boost/filesystem/operations.hpp>
31 #include <boost/filesystem/exception.hpp>
36 using support::ascii_lowercase;
37 using support::contains;
38 using support::FileName;
39 using support::getStringFromVector;
40 using support::getVectorFromString;
42 using support::prefixIs;
45 using support::tokenPos;
54 namespace fs = boost::filesystem;
59 vector<string> const init_possible_cite_commands()
61 char const * const pos[] = {
62 "cite", "citet", "citep", "citealt", "citealp",
63 "citeauthor", "citeyear", "citeyearpar",
64 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
65 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
66 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
68 "footcite", "footcitet", "footcitep", "footcitealt",
69 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
70 "citefield", "citetitle", "cite*"
72 size_t const size_pos = sizeof(pos) / sizeof(pos[0]);
74 return vector<string>(pos, pos + size_pos);
78 vector<string> const & possible_cite_commands()
80 static vector<string> const pos = init_possible_cite_commands();
85 bool is_possible_cite_command(string const & input)
87 vector<string> const & possibles = possible_cite_commands();
88 vector<string>::const_iterator const end = possibles.end();
89 return std::find(possibles.begin(), end, input) != end;
93 string const default_cite_command(biblio::CiteEngine engine)
97 case biblio::ENGINE_BASIC:
100 case biblio::ENGINE_NATBIB_AUTHORYEAR:
103 case biblio::ENGINE_NATBIB_NUMERICAL:
106 case biblio::ENGINE_JURABIB:
115 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
117 string const default_str = default_cite_command(engine);
118 if (!is_possible_cite_command(input))
123 case biblio::ENGINE_BASIC:
124 output = default_str;
127 case biblio::ENGINE_NATBIB_AUTHORYEAR:
128 case biblio::ENGINE_NATBIB_NUMERICAL:
129 if (input == "cite" || input == "citefield" ||
130 input == "citetitle" || input == "cite*")
131 output = default_str;
132 else if (prefixIs(input, "foot"))
133 output = input.substr(4);
138 case biblio::ENGINE_JURABIB: {
139 // Jurabib does not support the 'uppercase' natbib style.
141 output = string(1, 'c') + input.substr(1);
145 // Jurabib does not support the 'full' natbib style.
146 string::size_type const n = output.size() - 1;
147 if (output != "cite*" && output[n] == '*')
148 output = output.substr(0, n);
158 docstring const getNatbibLabel(Buffer const & buffer,
159 string const & citeType, docstring const & keyList,
160 docstring const & before, docstring const & after,
161 biblio::CiteEngine engine)
163 // Only start the process off after the buffer is loaded from file.
164 if (!buffer.fully_loaded())
168 typedef std::map<Buffer const *, BiblioInfo> CachedMap;
169 static CachedMap cached_keys;
171 // and cache the timestamp of the bibliography files.
172 static std::map<FileName, time_t> bibfileStatus;
176 vector<FileName> const & bibfilesCache = buffer.getBibfilesCache();
177 // compare the cached timestamps with the actual ones.
178 bool changed = false;
179 for (vector<FileName>::const_iterator it = bibfilesCache.begin();
180 it != bibfilesCache.end(); ++ it) {
181 FileName const f = *it;
183 std::time_t lastw = fs::last_write_time(f.toFilesystemEncoding());
184 if (lastw != bibfileStatus[f]) {
186 bibfileStatus[f] = lastw;
189 catch (fs::filesystem_error & fserr) {
191 lyxerr << "Couldn't find or read bibtex file "
193 LYXERR(Debug::DEBUG) << "Fs error: "
194 << fserr.what() << endl;
198 // build the list only if the bibfiles have been changed
199 if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
200 biblist.fillWithBibKeys(&buffer);
201 cached_keys[&buffer] = biblist;
203 // use the cached keys
204 biblist = cached_keys[&buffer];
209 // the natbib citation-styles
210 // CITET: author (year)
211 // CITEP: (author,year)
212 // CITEALT: author year
213 // CITEALP: author, year
214 // CITEAUTHOR: author
216 // CITEYEARPAR: (year)
217 // jurabib supports these plus
218 // CITE: author/<before field>
220 // We don't currently use the full or forceUCase fields.
221 string cite_type = asValidLatexCommand(citeType, engine);
222 if (cite_type[0] == 'C')
223 //If we were going to use them, this would mean ForceUCase
224 cite_type = string(1, 'c') + cite_type.substr(1);
225 if (cite_type[cite_type.size() - 1] == '*')
226 //and this would mean FULL
227 cite_type = cite_type.substr(0, cite_type.size() - 1);
229 docstring before_str;
230 if (!before.empty()) {
231 // In CITET and CITEALT mode, the "before" string is
232 // attached to the label associated with each and every key.
233 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
234 // to the front of the whole only.
235 // In other modes, it is not used at all.
236 if (cite_type == "citet" ||
237 cite_type == "citealt" ||
238 cite_type == "citep" ||
239 cite_type == "citealp" ||
240 cite_type == "citeyearpar")
241 before_str = before + ' ';
242 // In CITE (jurabib), the "before" string is used to attach
243 // the annotator (of legal texts) to the author(s) of the
245 else if (cite_type == "cite")
246 before_str = '/' + before;
250 if (!after.empty()) {
251 // The "after" key is appended only to the end of the whole.
252 after_str = ", " + after;
255 // One day, these might be tunable (as they are in BibTeX).
256 char const op = '('; // opening parenthesis.
257 char const cp = ')'; // closing parenthesis.
258 // puctuation mark separating citation entries.
259 char const * const sep = ";";
261 docstring const op_str(' ' + docstring(1, op));
262 docstring const cp_str(docstring(1, cp) + ' ');
263 docstring const sep_str(from_ascii(sep) + ' ');
266 vector<docstring> keys = getVectorFromString(keyList);
267 vector<docstring>::const_iterator it = keys.begin();
268 vector<docstring>::const_iterator end = keys.end();
269 for (; it != end; ++it) {
270 // get the bibdata corresponding to the key
271 docstring const author(biblist.getAbbreviatedAuthor(*it));
272 docstring const year(biblist.getYear(*it));
274 // Something isn't right. Fail safely.
275 if (author.empty() || year.empty())
278 // authors1/<before>; ... ;
279 // authors_last, <after>
280 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
281 if (it == keys.begin())
282 label += author + before_str + sep_str;
284 label += author + sep_str;
286 // (authors1 (<before> year); ... ;
287 // authors_last (<before> year, <after>)
288 } else if (cite_type == "citet") {
290 case biblio::ENGINE_NATBIB_AUTHORYEAR:
291 label += author + op_str + before_str +
294 case biblio::ENGINE_NATBIB_NUMERICAL:
295 label += author + op_str + before_str + '#' + *it + cp + sep_str;
297 case biblio::ENGINE_JURABIB:
298 label += before_str + author + op_str +
301 case biblio::ENGINE_BASIC:
305 // author, year; author, year; ...
306 } else if (cite_type == "citep" ||
307 cite_type == "citealp") {
308 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
309 label += *it + sep_str;
311 label += author + ", " + year + sep_str;
314 // (authors1 <before> year;
315 // authors_last <before> year, <after>)
316 } else if (cite_type == "citealt") {
318 case biblio::ENGINE_NATBIB_AUTHORYEAR:
319 label += author + ' ' + before_str +
322 case biblio::ENGINE_NATBIB_NUMERICAL:
323 label += author + ' ' + before_str + '#' + *it + sep_str;
325 case biblio::ENGINE_JURABIB:
326 label += before_str + author + ' ' +
329 case biblio::ENGINE_BASIC:
333 // author; author; ...
334 } else if (cite_type == "citeauthor") {
335 label += author + sep_str;
338 } else if (cite_type == "citeyear" ||
339 cite_type == "citeyearpar") {
340 label += year + sep_str;
343 label = rtrim(rtrim(label), sep);
345 if (!after_str.empty()) {
346 if (cite_type == "citet") {
347 // insert "after" before last ')'
348 label.insert(label.size() - 1, after_str);
351 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
352 (cite_type == "citeauthor" ||
353 cite_type == "citeyear"));
359 if (!before_str.empty() && (cite_type == "citep" ||
360 cite_type == "citealp" ||
361 cite_type == "citeyearpar")) {
362 label = before_str + label;
365 if (cite_type == "citep" || cite_type == "citeyearpar")
366 label = op + label + cp;
372 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
374 docstring keys(keyList);
377 if (contains(keys, ',')) {
378 // Final comma allows while loop to cover all keys
379 keys = ltrim(split(keys, label, ',')) + ',';
380 while (contains(keys, ',')) {
382 keys = ltrim(split(keys, key, ','));
389 label += ", " + after;
391 return '[' + label + ']';
397 InsetCitation::InsetCitation(InsetCommandParams const & p)
398 : InsetCommand(p, "citation")
402 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
404 docstring const before = getParam("before");
405 docstring const after = getParam("after");
408 biblio::CiteEngine const engine = buffer.params().getEngine();
409 if (engine != biblio::ENGINE_BASIC) {
410 label = getNatbibLabel(buffer, getCmdName(), getParam("key"),
411 before, after, engine);
414 // Fallback to fail-safe
416 label = getBasicLabel(getParam("key"), after);
423 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
425 biblio::CiteEngine const engine = buffer.params().getEngine();
426 if (cache.params == params() && cache.engine == engine)
427 return cache.screen_label;
429 // The label has changed, so we have to re-create it.
430 docstring const glabel = generateLabel(buffer);
432 unsigned int const maxLabelChars = 45;
434 docstring label = glabel;
435 if (label.size() > maxLabelChars) {
436 label.erase(maxLabelChars-3);
440 cache.engine = engine;
441 cache.params = params();
442 cache.generated_label = glabel;
443 cache.screen_label = label;
449 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
450 OutputParams const &) const
454 if (cache.params == params() &&
455 cache.engine == buffer.params().getEngine())
456 str = cache.generated_label;
458 str = generateLabel(buffer);
467 docstring const cleanupWhitespace(docstring const & citelist)
469 docstring::const_iterator it = citelist.begin();
470 docstring::const_iterator end = citelist.end();
471 // Paranoia check: make sure that there is no whitespace in here
472 // -- at least not behind commas or at the beginning
474 char_type last = ',';
475 for (; it != end; ++it) {
478 if (*it != ' ' || last != ',')
484 // end anon namyspace
487 int InsetCitation::docbook(Buffer const &, odocstream & os,
488 OutputParams const &) const
491 << cleanupWhitespace(getParam("key"))
497 int InsetCitation::textString(Buffer const & buf, odocstream & os,
498 OutputParams const & op) const
500 return plaintext(buf, os, op);
504 // Have to overwrite the default InsetCommand method in order to check that
505 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
506 // citations and then changes his mind, turning natbib support off. The output
507 // should revert to \cite[]{}
508 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
509 OutputParams const &) const
511 biblio::CiteEngine cite_engine = buffer.params().getEngine();
513 docstring const cite_str = from_utf8(
514 asValidLatexCommand(getCmdName(), cite_engine));
516 os << "\\" << cite_str;
518 docstring const & before = getParam("before");
519 docstring const & after = getParam("after");
520 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
521 os << '[' << before << "][" << after << ']';
522 else if (!after.empty())
523 os << '[' << after << ']';
525 os << '{' << cleanupWhitespace(getParam("key")) << '}';
531 void InsetCitation::validate(LaTeXFeatures & features) const
533 switch (features.bufferParams().getEngine()) {
534 case biblio::ENGINE_BASIC:
536 case biblio::ENGINE_NATBIB_AUTHORYEAR:
537 case biblio::ENGINE_NATBIB_NUMERICAL:
538 features.require("natbib");
540 case biblio::ENGINE_JURABIB:
541 features.require("jurabib");
547 void InsetCitation::replaceContents(string const & from, string const & to)
549 if (tokenPos(getContents(), ',', from) != -1) {
550 vector<string> items = getVectorFromString(getContents());
551 replace(items.begin(), items.end(), from, to);
552 setContents(getStringFromVector(items));