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"
18 #include "DispatchResult.h"
19 #include "support/gettext.h"
20 #include "EmbeddedFiles.h"
21 #include "FuncRequest.h"
22 #include "LaTeXFeatures.h"
24 #include "support/debug.h"
25 #include "support/docstream.h"
26 #include "support/lstrings.h"
31 using namespace lyx::support;
37 vector<string> const init_possible_cite_commands()
39 char const * const possible[] = {
40 "cite", "nocite", "citet", "citep", "citealt", "citealp",
41 "citeauthor", "citeyear", "citeyearpar",
42 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
43 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
44 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
46 "footcite", "footcitet", "footcitep", "footcitealt",
47 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
48 "citefield", "citetitle", "cite*"
50 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
52 return vector<string>(possible, possible + size_possible);
56 vector<string> const & possible_cite_commands()
58 static vector<string> const possible = init_possible_cite_commands();
63 //FIXME See the header for the issue.
64 string const default_cite_command(biblio::CiteEngine engine)
68 case biblio::ENGINE_BASIC:
71 case biblio::ENGINE_NATBIB_AUTHORYEAR:
74 case biblio::ENGINE_NATBIB_NUMERICAL:
77 case biblio::ENGINE_JURABIB:
86 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
88 string const default_str = default_cite_command(engine);
89 if (!InsetCitation::isCompatibleCommand(input))
94 case biblio::ENGINE_BASIC:
98 case biblio::ENGINE_NATBIB_AUTHORYEAR:
99 case biblio::ENGINE_NATBIB_NUMERICAL:
100 if (input == "cite" || input == "citefield" ||
101 input == "citetitle" || input == "cite*")
102 output = default_str;
103 else if (prefixIs(input, "foot"))
104 output = input.substr(4);
109 case biblio::ENGINE_JURABIB: {
110 // Jurabib does not support the 'uppercase' natbib style.
112 output = string(1, 'c') + input.substr(1);
116 // Jurabib does not support the 'full' natbib style.
117 string::size_type const n = output.size() - 1;
118 if (output != "cite*" && output[n] == '*')
119 output = output.substr(0, n);
129 docstring const getComplexLabel(Buffer const & buffer,
130 string const & citeType, docstring const & keyList,
131 docstring const & before, docstring const & after,
132 biblio::CiteEngine engine)
134 // Only start the process off after the buffer is loaded from file.
135 if (!buffer.isFullyLoaded())
139 typedef map<Buffer const *, BiblioInfo> CachedMap;
140 static CachedMap cached_keys;
142 // and cache the timestamp of the bibliography files.
143 static map<FileName, time_t> bibfileStatus;
147 EmbeddedFileList const & bibfilesCache = buffer.getBibfilesCache();
148 // compare the cached timestamps with the actual ones.
149 bool changed = false;
150 for (EmbeddedFileList::const_iterator it = bibfilesCache.begin();
151 it != bibfilesCache.end(); ++ it) {
152 FileName const f = *it;
153 time_t lastw = f.lastModified();
154 if (lastw != bibfileStatus[f]) {
156 bibfileStatus[f] = lastw;
160 // build the list only if the bibfiles have been changed
161 if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
162 biblist.fillWithBibKeys(&buffer);
163 cached_keys[&buffer] = biblist;
165 // use the cached keys
166 biblist = cached_keys[&buffer];
172 // the natbib citation-styles
173 // CITET: author (year)
174 // CITEP: (author,year)
175 // CITEALT: author year
176 // CITEALP: author, year
177 // CITEAUTHOR: author
179 // CITEYEARPAR: (year)
180 // jurabib supports these plus
181 // CITE: author/<before field>
183 // We don't currently use the full or forceUCase fields.
184 string cite_type = asValidLatexCommand(citeType, engine);
185 if (cite_type[0] == 'C')
186 //If we were going to use them, this would mean ForceUCase
187 cite_type = string(1, 'c') + cite_type.substr(1);
188 if (cite_type[cite_type.size() - 1] == '*')
189 //and this would mean FULL
190 cite_type = cite_type.substr(0, cite_type.size() - 1);
192 docstring before_str;
193 if (!before.empty()) {
194 // In CITET and CITEALT mode, the "before" string is
195 // attached to the label associated with each and every key.
196 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
197 // to the front of the whole only.
198 // In other modes, it is not used at all.
199 if (cite_type == "citet" ||
200 cite_type == "citealt" ||
201 cite_type == "citep" ||
202 cite_type == "citealp" ||
203 cite_type == "citeyearpar")
204 before_str = before + ' ';
205 // In CITE (jurabib), the "before" string is used to attach
206 // the annotator (of legal texts) to the author(s) of the
208 else if (cite_type == "cite")
209 before_str = '/' + before;
213 // The "after" key is appended only to the end of the whole.
214 if (cite_type == "nocite")
215 after_str = " (" + _("not cited") + ')';
216 else if (!after.empty()) {
217 after_str = ", " + after;
220 // One day, these might be tunable (as they are in BibTeX).
221 char op, cp; // opening and closing parenthesis.
222 char * sep; // punctuation mark separating citation entries.
223 if (engine == biblio::ENGINE_BASIC) {
233 docstring const op_str = ' ' + docstring(1, op);
234 docstring const cp_str = docstring(1, cp) + ' ';
235 docstring const sep_str = from_ascii(sep) + ' ';
238 vector<docstring> keys = getVectorFromString(keyList);
239 vector<docstring>::const_iterator it = keys.begin();
240 vector<docstring>::const_iterator end = keys.end();
241 for (; it != end; ++it) {
242 // get the bibdata corresponding to the key
243 docstring const author(biblist.getAbbreviatedAuthor(*it));
244 docstring const year(biblist.getYear(*it));
246 // Something isn't right. Fail safely.
247 if (author.empty() || year.empty())
250 // authors1/<before>; ... ;
251 // authors_last, <after>
252 if (cite_type == "cite") {
253 if (engine == biblio::ENGINE_BASIC) {
254 label += *it + sep_str;
255 } else if (engine == biblio::ENGINE_JURABIB) {
256 if (it == keys.begin())
257 label += author + before_str + sep_str;
259 label += author + sep_str;
263 } else if (cite_type == "nocite") {
264 label += *it + sep_str;
266 // (authors1 (<before> year); ... ;
267 // authors_last (<before> year, <after>)
268 } else if (cite_type == "citet") {
270 case biblio::ENGINE_NATBIB_AUTHORYEAR:
271 label += author + op_str + before_str +
274 case biblio::ENGINE_NATBIB_NUMERICAL:
275 label += author + op_str + before_str + '#' + *it + cp + sep_str;
277 case biblio::ENGINE_JURABIB:
278 label += before_str + author + op_str +
281 case biblio::ENGINE_BASIC:
285 // author, year; author, year; ...
286 } else if (cite_type == "citep" ||
287 cite_type == "citealp") {
288 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
289 label += *it + sep_str;
291 label += author + ", " + year + sep_str;
294 // (authors1 <before> year;
295 // authors_last <before> year, <after>)
296 } else if (cite_type == "citealt") {
298 case biblio::ENGINE_NATBIB_AUTHORYEAR:
299 label += author + ' ' + before_str +
302 case biblio::ENGINE_NATBIB_NUMERICAL:
303 label += author + ' ' + before_str + '#' + *it + sep_str;
305 case biblio::ENGINE_JURABIB:
306 label += before_str + author + ' ' +
309 case biblio::ENGINE_BASIC:
313 // author; author; ...
314 } else if (cite_type == "citeauthor") {
315 label += author + sep_str;
318 } else if (cite_type == "citeyear" ||
319 cite_type == "citeyearpar") {
320 label += year + sep_str;
323 label = rtrim(rtrim(label), sep);
325 if (!after_str.empty()) {
326 if (cite_type == "citet") {
327 // insert "after" before last ')'
328 label.insert(label.size() - 1, after_str);
331 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
332 (cite_type == "citeauthor" ||
333 cite_type == "citeyear"));
339 if (!before_str.empty() && (cite_type == "citep" ||
340 cite_type == "citealp" ||
341 cite_type == "citeyearpar")) {
342 label = before_str + label;
345 if (cite_type == "citep" || cite_type == "citeyearpar" ||
346 (cite_type == "cite" && engine == biblio::ENGINE_BASIC) )
347 label = op + label + cp;
353 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
355 docstring keys = keyList;
358 if (contains(keys, ',')) {
359 // Final comma allows while loop to cover all keys
360 keys = ltrim(split(keys, label, ',')) + ',';
361 while (contains(keys, ',')) {
363 keys = ltrim(split(keys, key, ','));
370 label += ", " + after;
372 return '[' + label + ']';
378 ParamInfo InsetCitation::param_info_;
381 InsetCitation::InsetCitation(InsetCommandParams const & p)
382 : InsetCommand(p, "citation")
386 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
388 // standard cite does only take one argument if jurabib is
389 // not used, but jurabib extends this to two arguments, so
390 // we have to allow both here. InsetCitation takes care that
391 // LaTeX output is nevertheless correct.
392 if (param_info_.empty()) {
393 param_info_.add("after", true);
394 param_info_.add("before", true);
395 param_info_.add("key", false);
401 bool InsetCitation::isCompatibleCommand(string const & cmd)
403 vector<string> const & possibles = possible_cite_commands();
404 vector<string>::const_iterator const end = possibles.end();
405 return find(possibles.begin(), end, cmd) != end;
409 docstring const InsetCitation::generateLabel(Buffer const & buffer) const
411 docstring const before = getParam("before");
412 docstring const after = getParam("after");
415 biblio::CiteEngine const engine = buffer.params().getEngine();
416 label = getComplexLabel(buffer, getCmdName(), getParam("key"),
417 before, after, engine);
419 // Fallback to fail-safe
421 label = getBasicLabel(getParam("key"), after);
427 docstring const InsetCitation::getScreenLabel(Buffer const & buffer) const
429 biblio::CiteEngine const engine = buffer.params().getEngine();
430 if (cache.params == params() && cache.engine == engine)
431 return cache.screen_label;
433 // The label has changed, so we have to re-create it.
434 docstring const glabel = generateLabel(buffer);
436 unsigned int const maxLabelChars = 45;
438 docstring label = glabel;
439 if (label.size() > maxLabelChars) {
440 label.erase(maxLabelChars-3);
444 cache.engine = engine;
445 cache.params = params();
446 cache.generated_label = glabel;
447 cache.screen_label = label;
453 int InsetCitation::plaintext(Buffer const & buffer, odocstream & os,
454 OutputParams const &) const
458 if (cache.params == params() &&
459 cache.engine == buffer.params().getEngine())
460 str = cache.generated_label;
462 str = generateLabel(buffer);
469 static docstring const cleanupWhitespace(docstring const & citelist)
471 docstring::const_iterator it = citelist.begin();
472 docstring::const_iterator end = citelist.end();
473 // Paranoia check: make sure that there is no whitespace in here
474 // -- at least not behind commas or at the beginning
476 char_type last = ',';
477 for (; it != end; ++it) {
480 if (*it != ' ' || last != ',')
487 int InsetCitation::docbook(Buffer const &, odocstream & os,
488 OutputParams const &) const
490 os << from_ascii("<citation>")
491 << cleanupWhitespace(getParam("key"))
492 << from_ascii("</citation>");
497 void InsetCitation::textString(Buffer const & buf, odocstream & os) const
499 plaintext(buf, os, OutputParams(0));
503 // Have to overwrite the default InsetCommand method in order to check that
504 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
505 // citations and then changes his mind, turning natbib support off. The output
506 // should revert to \cite[]{}
507 int InsetCitation::latex(Buffer const & buffer, odocstream & os,
508 OutputParams const &) const
510 biblio::CiteEngine cite_engine = buffer.params().getEngine();
512 docstring const cite_str = from_utf8(
513 asValidLatexCommand(getCmdName(), cite_engine));
515 os << "\\" << cite_str;
517 docstring const & before = getParam("before");
518 docstring const & after = getParam("after");
519 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
520 os << '[' << before << "][" << after << ']';
521 else if (!after.empty())
522 os << '[' << after << ']';
524 os << '{' << cleanupWhitespace(getParam("key")) << '}';
530 void InsetCitation::validate(LaTeXFeatures & features) const
532 switch (features.bufferParams().getEngine()) {
533 case biblio::ENGINE_BASIC:
535 case biblio::ENGINE_NATBIB_AUTHORYEAR:
536 case biblio::ENGINE_NATBIB_NUMERICAL:
537 features.require("natbib");
539 case biblio::ENGINE_JURABIB:
540 features.require("jurabib");