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 "EmbeddedFiles.h"
20 #include "FuncRequest.h"
21 #include "LaTeXFeatures.h"
22 #include "ParIterator.h"
23 #include "TocBackend.h"
25 #include "support/debug.h"
26 #include "support/docstream.h"
27 #include "support/gettext.h"
28 #include "support/lstrings.h"
33 using namespace lyx::support;
39 vector<string> const init_possible_cite_commands()
41 char const * const possible[] = {
42 "cite", "nocite", "citet", "citep", "citealt", "citealp",
43 "citeauthor", "citeyear", "citeyearpar",
44 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
45 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
46 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
48 "footcite", "footcitet", "footcitep", "footcitealt",
49 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
50 "citefield", "citetitle", "cite*"
52 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
54 return vector<string>(possible, possible + size_possible);
58 vector<string> const & possible_cite_commands()
60 static vector<string> const possible = init_possible_cite_commands();
65 //FIXME See the header for the issue.
66 string const default_cite_command(biblio::CiteEngine engine)
70 case biblio::ENGINE_BASIC:
73 case biblio::ENGINE_NATBIB_AUTHORYEAR:
76 case biblio::ENGINE_NATBIB_NUMERICAL:
79 case biblio::ENGINE_JURABIB:
88 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
90 string const default_str = default_cite_command(engine);
91 if (!InsetCitation::isCompatibleCommand(input))
96 case biblio::ENGINE_BASIC:
100 case biblio::ENGINE_NATBIB_AUTHORYEAR:
101 case biblio::ENGINE_NATBIB_NUMERICAL:
102 if (input == "cite" || input == "citefield" ||
103 input == "citetitle" || input == "cite*")
104 output = default_str;
105 else if (prefixIs(input, "foot"))
106 output = input.substr(4);
111 case biblio::ENGINE_JURABIB: {
112 // Jurabib does not support the 'uppercase' natbib style.
114 output = string(1, 'c') + input.substr(1);
118 // Jurabib does not support the 'full' natbib style.
119 string::size_type const n = output.size() - 1;
120 if (output != "cite*" && output[n] == '*')
121 output = output.substr(0, n);
131 docstring getComplexLabel(Buffer const & buffer,
132 string const & citeType, docstring const & keyList,
133 docstring const & before, docstring const & after,
134 biblio::CiteEngine engine)
136 // Only start the process off after the buffer is loaded from file.
137 if (!buffer.isFullyLoaded())
141 typedef map<Buffer const *, BiblioInfo> CachedMap;
142 static CachedMap cached_keys;
144 // and cache the timestamp of the bibliography files.
145 static map<FileName, time_t> bibfileStatus;
149 EmbeddedFileList const & bibfilesCache = buffer.getBibfilesCache();
150 // compare the cached timestamps with the actual ones.
151 bool changed = false;
152 for (EmbeddedFileList::const_iterator it = bibfilesCache.begin();
153 it != bibfilesCache.end(); ++ it) {
154 FileName const f = *it;
155 time_t lastw = f.lastModified();
156 if (lastw != bibfileStatus[f]) {
158 bibfileStatus[f] = lastw;
162 // build the list only if the bibfiles have been changed
163 if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
164 biblist.fillWithBibKeys(&buffer);
165 cached_keys[&buffer] = biblist;
167 // use the cached keys
168 biblist = cached_keys[&buffer];
174 // the natbib citation-styles
175 // CITET: author (year)
176 // CITEP: (author,year)
177 // CITEALT: author year
178 // CITEALP: author, year
179 // CITEAUTHOR: author
181 // CITEYEARPAR: (year)
182 // jurabib supports these plus
183 // CITE: author/<before field>
185 // We don't currently use the full or forceUCase fields.
186 string cite_type = asValidLatexCommand(citeType, engine);
187 if (cite_type[0] == 'C')
188 //If we were going to use them, this would mean ForceUCase
189 cite_type = string(1, 'c') + cite_type.substr(1);
190 if (cite_type[cite_type.size() - 1] == '*')
191 //and this would mean FULL
192 cite_type = cite_type.substr(0, cite_type.size() - 1);
194 docstring before_str;
195 if (!before.empty()) {
196 // In CITET and CITEALT mode, the "before" string is
197 // attached to the label associated with each and every key.
198 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
199 // to the front of the whole only.
200 // In other modes, it is not used at all.
201 if (cite_type == "citet" ||
202 cite_type == "citealt" ||
203 cite_type == "citep" ||
204 cite_type == "citealp" ||
205 cite_type == "citeyearpar")
206 before_str = before + ' ';
207 // In CITE (jurabib), the "before" string is used to attach
208 // the annotator (of legal texts) to the author(s) of the
210 else if (cite_type == "cite")
211 before_str = '/' + before;
215 // The "after" key is appended only to the end of the whole.
216 if (cite_type == "nocite")
217 after_str = " (" + _("not cited") + ')';
218 else if (!after.empty()) {
219 after_str = ", " + after;
222 // One day, these might be tunable (as they are in BibTeX).
223 char op, cp; // opening and closing parenthesis.
224 char * sep; // punctuation mark separating citation entries.
225 if (engine == biblio::ENGINE_BASIC) {
235 docstring const op_str = ' ' + docstring(1, op);
236 docstring const cp_str = docstring(1, cp) + ' ';
237 docstring const sep_str = from_ascii(sep) + ' ';
240 vector<docstring> keys = getVectorFromString(keyList);
241 vector<docstring>::const_iterator it = keys.begin();
242 vector<docstring>::const_iterator end = keys.end();
243 for (; it != end; ++it) {
244 // get the bibdata corresponding to the key
245 docstring const author(biblist.getAbbreviatedAuthor(*it));
246 docstring const year(biblist.getYear(*it));
248 // Something isn't right. Fail safely.
249 if (author.empty() || year.empty())
252 // authors1/<before>; ... ;
253 // authors_last, <after>
254 if (cite_type == "cite") {
255 if (engine == biblio::ENGINE_BASIC) {
256 label += *it + sep_str;
257 } else if (engine == biblio::ENGINE_JURABIB) {
258 if (it == keys.begin())
259 label += author + before_str + sep_str;
261 label += author + sep_str;
265 } else if (cite_type == "nocite") {
266 label += *it + sep_str;
268 // (authors1 (<before> year); ... ;
269 // authors_last (<before> year, <after>)
270 } else if (cite_type == "citet") {
272 case biblio::ENGINE_NATBIB_AUTHORYEAR:
273 label += author + op_str + before_str +
276 case biblio::ENGINE_NATBIB_NUMERICAL:
277 label += author + op_str + before_str + '#' + *it + cp + sep_str;
279 case biblio::ENGINE_JURABIB:
280 label += before_str + author + op_str +
283 case biblio::ENGINE_BASIC:
287 // author, year; author, year; ...
288 } else if (cite_type == "citep" ||
289 cite_type == "citealp") {
290 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
291 label += *it + sep_str;
293 label += author + ", " + year + sep_str;
296 // (authors1 <before> year;
297 // authors_last <before> year, <after>)
298 } else if (cite_type == "citealt") {
300 case biblio::ENGINE_NATBIB_AUTHORYEAR:
301 label += author + ' ' + before_str +
304 case biblio::ENGINE_NATBIB_NUMERICAL:
305 label += author + ' ' + before_str + '#' + *it + sep_str;
307 case biblio::ENGINE_JURABIB:
308 label += before_str + author + ' ' +
311 case biblio::ENGINE_BASIC:
315 // author; author; ...
316 } else if (cite_type == "citeauthor") {
317 label += author + sep_str;
320 } else if (cite_type == "citeyear" ||
321 cite_type == "citeyearpar") {
322 label += year + sep_str;
325 label = rtrim(rtrim(label), sep);
327 if (!after_str.empty()) {
328 if (cite_type == "citet") {
329 // insert "after" before last ')'
330 label.insert(label.size() - 1, after_str);
333 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
334 (cite_type == "citeauthor" ||
335 cite_type == "citeyear"));
341 if (!before_str.empty() && (cite_type == "citep" ||
342 cite_type == "citealp" ||
343 cite_type == "citeyearpar")) {
344 label = before_str + label;
347 if (cite_type == "citep" || cite_type == "citeyearpar" ||
348 (cite_type == "cite" && engine == biblio::ENGINE_BASIC) )
349 label = op + label + cp;
355 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
357 docstring keys = keyList;
360 if (contains(keys, ',')) {
361 // Final comma allows while loop to cover all keys
362 keys = ltrim(split(keys, label, ',')) + ',';
363 while (contains(keys, ',')) {
365 keys = ltrim(split(keys, key, ','));
372 label += ", " + after;
374 return '[' + label + ']';
380 ParamInfo InsetCitation::param_info_;
383 InsetCitation::InsetCitation(InsetCommandParams const & p)
384 : InsetCommand(p, "citation")
388 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
390 // standard cite does only take one argument if jurabib is
391 // not used, but jurabib extends this to two arguments, so
392 // we have to allow both here. InsetCitation takes care that
393 // LaTeX output is nevertheless correct.
394 if (param_info_.empty()) {
395 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
396 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
397 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
403 bool InsetCitation::isCompatibleCommand(string const & cmd)
405 vector<string> const & possibles = possible_cite_commands();
406 vector<string>::const_iterator const end = possibles.end();
407 return find(possibles.begin(), end, cmd) != end;
411 docstring InsetCitation::generateLabel() const
413 docstring const before = getParam("before");
414 docstring const after = getParam("after");
417 biblio::CiteEngine const engine = buffer().params().getEngine();
418 label = getComplexLabel(buffer(), getCmdName(), getParam("key"),
419 before, after, engine);
421 // Fallback to fail-safe
423 label = getBasicLabel(getParam("key"), after);
429 docstring InsetCitation::screenLabel() const
431 return cache.screen_label;
435 void InsetCitation::updateLabels(ParIterator const &)
437 biblio::CiteEngine const engine = buffer().params().getEngine();
438 if (cache.params == params() && cache.engine == engine)
441 // The label has changed, so we have to re-create it.
442 docstring const glabel = generateLabel();
444 unsigned int const maxLabelChars = 45;
446 docstring label = glabel;
447 if (label.size() > maxLabelChars) {
448 label.erase(maxLabelChars-3);
452 cache.engine = engine;
453 cache.params = params();
454 cache.generated_label = glabel;
455 cache.screen_label = label;
459 void InsetCitation::addToToc(ParConstIterator const & cpit) const
461 Toc & toc = buffer().tocBackend().toc("citation");
462 toc.push_back(TocItem(cpit, 0, cache.screen_label));
466 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
470 if (cache.params == params() &&
471 cache.engine == buffer().params().getEngine())
472 str = cache.generated_label;
474 str = generateLabel();
481 static docstring const cleanupWhitespace(docstring const & citelist)
483 docstring::const_iterator it = citelist.begin();
484 docstring::const_iterator end = citelist.end();
485 // Paranoia check: make sure that there is no whitespace in here
486 // -- at least not behind commas or at the beginning
488 char_type last = ',';
489 for (; it != end; ++it) {
492 if (*it != ' ' || last != ',')
499 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
501 os << from_ascii("<citation>")
502 << cleanupWhitespace(getParam("key"))
503 << from_ascii("</citation>");
508 void InsetCitation::textString(odocstream & os) const
510 plaintext(os, OutputParams(0));
514 // Have to overwrite the default InsetCommand method in order to check that
515 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
516 // citations and then changes his mind, turning natbib support off. The output
517 // should revert to \cite[]{}
518 int InsetCitation::latex(odocstream & os, OutputParams const &) const
520 biblio::CiteEngine cite_engine = buffer().params().getEngine();
522 docstring const cite_str = from_utf8(
523 asValidLatexCommand(getCmdName(), cite_engine));
525 os << "\\" << cite_str;
527 docstring const & before = getParam("before");
528 docstring const & after = getParam("after");
529 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
530 os << '[' << before << "][" << after << ']';
531 else if (!after.empty())
532 os << '[' << after << ']';
534 os << '{' << cleanupWhitespace(getParam("key")) << '}';
540 void InsetCitation::validate(LaTeXFeatures & features) const
542 switch (features.bufferParams().getEngine()) {
543 case biblio::ENGINE_BASIC:
545 case biblio::ENGINE_NATBIB_AUTHORYEAR:
546 case biblio::ENGINE_NATBIB_NUMERICAL:
547 features.require("natbib");
549 case biblio::ENGINE_JURABIB:
550 features.require("jurabib");