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/lstrings.h"
27 #include <boost/filesystem/operations.hpp>
28 #include <boost/filesystem/exception.hpp>
33 using support::FileName;
34 using support::getStringFromVector;
35 using support::getVectorFromString;
37 using support::prefixIs;
40 using support::tokenPos;
46 namespace fs = boost::filesystem;
51 vector<string> const init_possible_cite_commands()
53 char const * const possible[] = {
54 "cite", "citet", "citep", "citealt", "citealp",
55 "citeauthor", "citeyear", "citeyearpar",
56 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
57 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
58 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
60 "footcite", "footcitet", "footcitep", "footcitealt",
61 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
62 "citefield", "citetitle", "cite*"
64 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
66 return vector<string>(possible, possible + size_possible);
70 vector<string> const & possible_cite_commands()
72 static vector<string> const possible = init_possible_cite_commands();
77 //FIXME See the header for the issue.
78 string const default_cite_command(biblio::CiteEngine engine)
82 case biblio::ENGINE_BASIC:
85 case biblio::ENGINE_NATBIB_AUTHORYEAR:
88 case biblio::ENGINE_NATBIB_NUMERICAL:
91 case biblio::ENGINE_JURABIB:
100 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
102 string const default_str = default_cite_command(engine);
103 if (!InsetCitation::isCompatibleCommand(input))
108 case biblio::ENGINE_BASIC:
109 output = default_str;
112 case biblio::ENGINE_NATBIB_AUTHORYEAR:
113 case biblio::ENGINE_NATBIB_NUMERICAL:
114 if (input == "cite" || input == "citefield" ||
115 input == "citetitle" || input == "cite*")
116 output = default_str;
117 else if (prefixIs(input, "foot"))
118 output = input.substr(4);
123 case biblio::ENGINE_JURABIB: {
124 // Jurabib does not support the 'uppercase' natbib style.
126 output = string(1, 'c') + input.substr(1);
130 // Jurabib does not support the 'full' natbib style.
131 string::size_type const n = output.size() - 1;
132 if (output != "cite*" && output[n] == '*')
133 output = output.substr(0, n);
143 docstring const getNatbibLabel(Buffer const & buffer,
144 string const & citeType, docstring const & keyList,
145 docstring const & before, docstring const & after,
146 biblio::CiteEngine engine)
148 // Only start the process off after the buffer is loaded from file.
149 if (!buffer.isFullyLoaded())
153 typedef std::map<Buffer const *, BiblioInfo> CachedMap;
154 static CachedMap cached_keys;
156 // and cache the timestamp of the bibliography files.
157 static std::map<FileName, time_t> bibfileStatus;
161 vector<FileName> const & bibfilesCache = buffer.getBibfilesCache();
162 // compare the cached timestamps with the actual ones.
163 bool changed = false;
164 for (vector<FileName>::const_iterator it = bibfilesCache.begin();
165 it != bibfilesCache.end(); ++ it) {
166 FileName const f = *it;
168 std::time_t lastw = f.lastModified();
169 if (lastw != bibfileStatus[f]) {
171 bibfileStatus[f] = lastw;
174 catch (fs::filesystem_error & fserr) {
176 lyxerr << "Couldn't find or read bibtex file "
178 LYXERR(Debug::DEBUG) << "Fs error: "
179 << fserr.what() << endl;
183 // build the list only if the bibfiles have been changed
184 if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
185 biblist.fillWithBibKeys(&buffer);
186 cached_keys[&buffer] = biblist;
188 // use the cached keys
189 biblist = cached_keys[&buffer];
195 // the natbib citation-styles
196 // CITET: author (year)
197 // CITEP: (author,year)
198 // CITEALT: author year
199 // CITEALP: author, year
200 // CITEAUTHOR: author
202 // CITEYEARPAR: (year)
203 // jurabib supports these plus
204 // CITE: author/<before field>
206 // We don't currently use the full or forceUCase fields.
207 string cite_type = asValidLatexCommand(citeType, engine);
208 if (cite_type[0] == 'C')
209 //If we were going to use them, this would mean ForceUCase
210 cite_type = string(1, 'c') + cite_type.substr(1);
211 if (cite_type[cite_type.size() - 1] == '*')
212 //and this would mean FULL
213 cite_type = cite_type.substr(0, cite_type.size() - 1);
215 docstring before_str;
216 if (!before.empty()) {
217 // In CITET and CITEALT mode, the "before" string is
218 // attached to the label associated with each and every key.
219 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
220 // to the front of the whole only.
221 // In other modes, it is not used at all.
222 if (cite_type == "citet" ||
223 cite_type == "citealt" ||
224 cite_type == "citep" ||
225 cite_type == "citealp" ||
226 cite_type == "citeyearpar")
227 before_str = before + ' ';
228 // In CITE (jurabib), the "before" string is used to attach
229 // the annotator (of legal texts) to the author(s) of the
231 else if (cite_type == "cite")
232 before_str = '/' + before;
236 if (!after.empty()) {
237 // The "after" key is appended only to the end of the whole.
238 after_str = ", " + after;
241 // One day, these might be tunable (as they are in BibTeX).
242 char const op = '('; // opening parenthesis.
243 char const cp = ')'; // closing parenthesis.
244 // puctuation mark separating citation entries.
245 char const * const sep = ";";
247 docstring const op_str = ' ' + docstring(1, op);
248 docstring const cp_str = docstring(1, cp) + ' ';
249 docstring const sep_str = from_ascii(sep) + ' ';
252 vector<docstring> keys = getVectorFromString(keyList);
253 vector<docstring>::const_iterator it = keys.begin();
254 vector<docstring>::const_iterator end = keys.end();
255 for (; it != end; ++it) {
256 // get the bibdata corresponding to the key
257 docstring const author(biblist.getAbbreviatedAuthor(*it));
258 docstring const year(biblist.getYear(*it));
260 // Something isn't right. Fail safely.
261 if (author.empty() || year.empty())
264 // authors1/<before>; ... ;
265 // authors_last, <after>
266 if (cite_type == "cite" && engine == biblio::ENGINE_JURABIB) {
267 if (it == keys.begin())
268 label += author + before_str + sep_str;
270 label += author + sep_str;
272 // (authors1 (<before> year); ... ;
273 // authors_last (<before> year, <after>)
274 } else if (cite_type == "citet") {
276 case biblio::ENGINE_NATBIB_AUTHORYEAR:
277 label += author + op_str + before_str +
280 case biblio::ENGINE_NATBIB_NUMERICAL:
281 label += author + op_str + before_str + '#' + *it + cp + sep_str;
283 case biblio::ENGINE_JURABIB:
284 label += before_str + author + op_str +
287 case biblio::ENGINE_BASIC:
291 // author, year; author, year; ...
292 } else if (cite_type == "citep" ||
293 cite_type == "citealp") {
294 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
295 label += *it + sep_str;
297 label += author + ", " + year + sep_str;
300 // (authors1 <before> year;
301 // authors_last <before> year, <after>)
302 } else if (cite_type == "citealt") {
304 case biblio::ENGINE_NATBIB_AUTHORYEAR:
305 label += author + ' ' + before_str +
308 case biblio::ENGINE_NATBIB_NUMERICAL:
309 label += author + ' ' + before_str + '#' + *it + sep_str;
311 case biblio::ENGINE_JURABIB:
312 label += before_str + author + ' ' +
315 case biblio::ENGINE_BASIC:
319 // author; author; ...
320 } else if (cite_type == "citeauthor") {
321 label += author + sep_str;
324 } else if (cite_type == "citeyear" ||
325 cite_type == "citeyearpar") {
326 label += year + sep_str;
329 label = rtrim(rtrim(label), sep);
331 if (!after_str.empty()) {
332 if (cite_type == "citet") {
333 // insert "after" before last ')'
334 label.insert(label.size() - 1, after_str);
337 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
338 (cite_type == "citeauthor" ||
339 cite_type == "citeyear"));
345 if (!before_str.empty() && (cite_type == "citep" ||
346 cite_type == "citealp" ||
347 cite_type == "citeyearpar")) {
348 label = before_str + label;
351 if (cite_type == "citep" || cite_type == "citeyearpar")
352 label = op + label + cp;
358 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
360 using support::contains;
362 docstring keys = keyList;
365 if (contains(keys, ',')) {
366 // Final comma allows while loop to cover all keys
367 keys = ltrim(split(keys, label, ',')) + ',';
368 while (contains(keys, ',')) {
370 keys = ltrim(split(keys, key, ','));
377 label += ", " + after;
379 return '[' + label + ']';
385 InsetCitation::InsetCitation(InsetCommandParams const & p)
386 : InsetCommand(p, "citation")
390 CommandInfo const * InsetCitation::findInfo(std::string const & /* cmdName */)
392 // standard cite does only take one argument if jurabib is
393 // not used, but jurabib extends this to two arguments, so
394 // we have to allow both here. InsetCitation takes care that
395 // LaTeX output is nevertheless correct.
396 static const char * const paramnames[] =
397 {"after", "before", "key", ""};
398 static const bool isoptional[] = {true, true, false};
399 static const CommandInfo info = {3, paramnames, isoptional};
404 bool InsetCitation::isCompatibleCommand(std::string const & cmd)
406 vector<string> const & possibles = possible_cite_commands();
407 vector<string>::const_iterator const end = possibles.end();
408 return std::find(possibles.begin(), end, cmd) != end;
412 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
414 docstring const before = getParam("before");
415 docstring const after = getParam("after");
418 biblio::CiteEngine const engine = buffer.params().getEngine();
419 if (engine != biblio::ENGINE_BASIC) {
420 label = getNatbibLabel(buffer, getCmdName(), getParam("key"),
421 before, after, engine);
424 // Fallback to fail-safe
426 label = getBasicLabel(getParam("key"), after);
433 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
435 biblio::CiteEngine const engine = buffer.params().getEngine();
436 if (cache.params == params() && cache.engine == engine)
437 return cache.screen_label;
439 // The label has changed, so we have to re-create it.
440 docstring const glabel = generateLabel(buffer);
442 unsigned int const maxLabelChars = 45;
444 docstring label = glabel;
445 if (label.size() > maxLabelChars) {
446 label.erase(maxLabelChars-3);
450 cache.engine = engine;
451 cache.params = params();
452 cache.generated_label = glabel;
453 cache.screen_label = label;
459 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
460 OutputParams const &) const
464 if (cache.params == params() &&
465 cache.engine == buffer.params().getEngine())
466 str = cache.generated_label;
468 str = generateLabel(buffer);
475 static docstring const cleanupWhitespace(docstring const & citelist)
477 docstring::const_iterator it = citelist.begin();
478 docstring::const_iterator end = citelist.end();
479 // Paranoia check: make sure that there is no whitespace in here
480 // -- at least not behind commas or at the beginning
482 char_type last = ',';
483 for (; it != end; ++it) {
486 if (*it != ' ' || last != ',')
493 int InsetCitation::docbook(Buffer const &, odocstream & os,
494 OutputParams const &) const
497 << cleanupWhitespace(getParam("key"))
503 int InsetCitation::textString(Buffer const & buf, odocstream & os,
504 OutputParams const & op) const
506 return plaintext(buf, os, op);
510 // Have to overwrite the default InsetCommand method in order to check that
511 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
512 // citations and then changes his mind, turning natbib support off. The output
513 // should revert to \cite[]{}
514 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
515 OutputParams const &) const
517 biblio::CiteEngine cite_engine = buffer.params().getEngine();
519 docstring const cite_str = from_utf8(
520 asValidLatexCommand(getCmdName(), cite_engine));
522 os << "\\" << cite_str;
524 docstring const & before = getParam("before");
525 docstring const & after = getParam("after");
526 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
527 os << '[' << before << "][" << after << ']';
528 else if (!after.empty())
529 os << '[' << after << ']';
531 os << '{' << cleanupWhitespace(getParam("key")) << '}';
537 void InsetCitation::validate(LaTeXFeatures & features) const
539 switch (features.bufferParams().getEngine()) {
540 case biblio::ENGINE_BASIC:
542 case biblio::ENGINE_NATBIB_AUTHORYEAR:
543 case biblio::ENGINE_NATBIB_NUMERICAL:
544 features.require("natbib");
546 case biblio::ENGINE_JURABIB:
547 features.require("jurabib");