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 "buffer_funcs.h"
18 #include "BufferParams.h"
19 #include "DispatchResult.h"
20 #include "EmbeddedFiles.h"
21 #include "FuncRequest.h"
22 #include "LaTeXFeatures.h"
23 #include "ParIterator.h"
24 #include "TocBackend.h"
26 #include "support/debug.h"
27 #include "support/docstream.h"
28 #include "support/gettext.h"
29 #include "support/lstrings.h"
34 using namespace lyx::support;
40 vector<string> const init_possible_cite_commands()
42 char const * const possible[] = {
43 "cite", "nocite", "citet", "citep", "citealt", "citealp",
44 "citeauthor", "citeyear", "citeyearpar",
45 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
46 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
47 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
49 "footcite", "footcitet", "footcitep", "footcitealt",
50 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
51 "citefield", "citetitle", "cite*"
53 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
55 return vector<string>(possible, possible + size_possible);
59 vector<string> const & possible_cite_commands()
61 static vector<string> const possible = init_possible_cite_commands();
66 //FIXME See the header for the issue.
67 string const default_cite_command(biblio::CiteEngine engine)
71 case biblio::ENGINE_BASIC:
74 case biblio::ENGINE_NATBIB_AUTHORYEAR:
77 case biblio::ENGINE_NATBIB_NUMERICAL:
80 case biblio::ENGINE_JURABIB:
89 asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
91 string const default_str = default_cite_command(engine);
92 if (!InsetCitation::isCompatibleCommand(input))
97 case biblio::ENGINE_BASIC:
101 case biblio::ENGINE_NATBIB_AUTHORYEAR:
102 case biblio::ENGINE_NATBIB_NUMERICAL:
103 if (input == "cite" || input == "citefield" ||
104 input == "citetitle" || input == "cite*")
105 output = default_str;
106 else if (prefixIs(input, "foot"))
107 output = input.substr(4);
112 case biblio::ENGINE_JURABIB: {
113 // Jurabib does not support the 'uppercase' natbib style.
115 output = string(1, 'c') + input.substr(1);
119 // Jurabib does not support the 'full' natbib style.
120 string::size_type const n = output.size() - 1;
121 if (output != "cite*" && output[n] == '*')
122 output = output.substr(0, n);
132 docstring getComplexLabel(Buffer const & buffer,
133 string const & citeType, docstring const & keyList,
134 docstring const & before, docstring const & after,
135 biblio::CiteEngine engine)
137 // Only start the process off after the buffer is loaded from file.
138 if (!buffer.isFullyLoaded())
142 typedef map<Buffer const *, BiblioInfo> CachedMap;
143 static CachedMap cached_keys;
145 // and cache the timestamp of the bibliography files.
146 static map<FileName, time_t> bibfileStatus;
150 EmbeddedFileList const & bibfilesCache = buffer.getBibfilesCache();
151 // compare the cached timestamps with the actual ones.
152 bool changed = false;
153 for (EmbeddedFileList::const_iterator it = bibfilesCache.begin();
154 it != bibfilesCache.end(); ++ it) {
155 FileName const f = *it;
156 time_t lastw = f.lastModified();
157 if (lastw != bibfileStatus[f]) {
159 bibfileStatus[f] = lastw;
163 // build the list only if the bibfiles have been changed
164 if (cached_keys[&buffer].empty() || bibfileStatus.empty() || changed) {
165 biblist.fillWithBibKeys(&buffer);
166 cached_keys[&buffer] = biblist;
168 // use the cached keys
169 biblist = cached_keys[&buffer];
175 // the natbib citation-styles
176 // CITET: author (year)
177 // CITEP: (author,year)
178 // CITEALT: author year
179 // CITEALP: author, year
180 // CITEAUTHOR: author
182 // CITEYEARPAR: (year)
183 // jurabib supports these plus
184 // CITE: author/<before field>
186 // We don't currently use the full or forceUCase fields.
187 string cite_type = asValidLatexCommand(citeType, engine);
188 if (cite_type[0] == 'C')
189 //If we were going to use them, this would mean ForceUCase
190 cite_type = string(1, 'c') + cite_type.substr(1);
191 if (cite_type[cite_type.size() - 1] == '*')
192 //and this would mean FULL
193 cite_type = cite_type.substr(0, cite_type.size() - 1);
195 docstring before_str;
196 if (!before.empty()) {
197 // In CITET and CITEALT mode, the "before" string is
198 // attached to the label associated with each and every key.
199 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
200 // to the front of the whole only.
201 // In other modes, it is not used at all.
202 if (cite_type == "citet" ||
203 cite_type == "citealt" ||
204 cite_type == "citep" ||
205 cite_type == "citealp" ||
206 cite_type == "citeyearpar")
207 before_str = before + ' ';
208 // In CITE (jurabib), the "before" string is used to attach
209 // the annotator (of legal texts) to the author(s) of the
211 else if (cite_type == "cite")
212 before_str = '/' + before;
216 // The "after" key is appended only to the end of the whole.
217 if (cite_type == "nocite")
218 after_str = " (" + _("not cited") + ')';
219 else if (!after.empty()) {
220 after_str = ", " + after;
223 // One day, these might be tunable (as they are in BibTeX).
224 char op, cp; // opening and closing parenthesis.
225 char * sep; // punctuation mark separating citation entries.
226 if (engine == biblio::ENGINE_BASIC) {
236 docstring const op_str = ' ' + docstring(1, op);
237 docstring const cp_str = docstring(1, cp) + ' ';
238 docstring const sep_str = from_ascii(sep) + ' ';
241 vector<docstring> keys = getVectorFromString(keyList);
242 vector<docstring>::const_iterator it = keys.begin();
243 vector<docstring>::const_iterator end = keys.end();
244 for (; it != end; ++it) {
245 // get the bibdata corresponding to the key
246 docstring const author(biblist.getAbbreviatedAuthor(*it));
247 docstring const year(biblist.getYear(*it));
249 // Something isn't right. Fail safely.
250 if (author.empty() || year.empty())
253 // authors1/<before>; ... ;
254 // authors_last, <after>
255 if (cite_type == "cite") {
256 if (engine == biblio::ENGINE_BASIC) {
257 label += *it + sep_str;
258 } else if (engine == biblio::ENGINE_JURABIB) {
259 if (it == keys.begin())
260 label += author + before_str + sep_str;
262 label += author + sep_str;
266 } else if (cite_type == "nocite") {
267 label += *it + sep_str;
269 // (authors1 (<before> year); ... ;
270 // authors_last (<before> year, <after>)
271 } else if (cite_type == "citet") {
273 case biblio::ENGINE_NATBIB_AUTHORYEAR:
274 label += author + op_str + before_str +
277 case biblio::ENGINE_NATBIB_NUMERICAL:
278 label += author + op_str + before_str + '#' + *it + cp + sep_str;
280 case biblio::ENGINE_JURABIB:
281 label += before_str + author + op_str +
284 case biblio::ENGINE_BASIC:
288 // author, year; author, year; ...
289 } else if (cite_type == "citep" ||
290 cite_type == "citealp") {
291 if (engine == biblio::ENGINE_NATBIB_NUMERICAL) {
292 label += *it + sep_str;
294 label += author + ", " + year + sep_str;
297 // (authors1 <before> year;
298 // authors_last <before> year, <after>)
299 } else if (cite_type == "citealt") {
301 case biblio::ENGINE_NATBIB_AUTHORYEAR:
302 label += author + ' ' + before_str +
305 case biblio::ENGINE_NATBIB_NUMERICAL:
306 label += author + ' ' + before_str + '#' + *it + sep_str;
308 case biblio::ENGINE_JURABIB:
309 label += before_str + author + ' ' +
312 case biblio::ENGINE_BASIC:
316 // author; author; ...
317 } else if (cite_type == "citeauthor") {
318 label += author + sep_str;
321 } else if (cite_type == "citeyear" ||
322 cite_type == "citeyearpar") {
323 label += year + sep_str;
326 label = rtrim(rtrim(label), sep);
328 if (!after_str.empty()) {
329 if (cite_type == "citet") {
330 // insert "after" before last ')'
331 label.insert(label.size() - 1, after_str);
334 !(engine == biblio::ENGINE_NATBIB_NUMERICAL &&
335 (cite_type == "citeauthor" ||
336 cite_type == "citeyear"));
342 if (!before_str.empty() && (cite_type == "citep" ||
343 cite_type == "citealp" ||
344 cite_type == "citeyearpar")) {
345 label = before_str + label;
348 if (cite_type == "citep" || cite_type == "citeyearpar" ||
349 (cite_type == "cite" && engine == biblio::ENGINE_BASIC) )
350 label = op + label + cp;
356 docstring const getBasicLabel(docstring const & keyList, docstring const & after)
358 docstring keys = keyList;
361 if (contains(keys, ',')) {
362 // Final comma allows while loop to cover all keys
363 keys = ltrim(split(keys, label, ',')) + ',';
364 while (contains(keys, ',')) {
366 keys = ltrim(split(keys, key, ','));
373 label += ", " + after;
375 return '[' + label + ']';
381 ParamInfo InsetCitation::param_info_;
384 InsetCitation::InsetCitation(InsetCommandParams const & p)
385 : InsetCommand(p, "citation")
389 void InsetCitation::initView()
391 // We need an update of the Buffer reference cache. This is achieved by
393 lyx::updateLabels(buffer());
397 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
399 // standard cite does only take one argument if jurabib is
400 // not used, but jurabib extends this to two arguments, so
401 // we have to allow both here. InsetCitation takes care that
402 // LaTeX output is nevertheless correct.
403 if (param_info_.empty()) {
404 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
405 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
406 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
412 bool InsetCitation::isCompatibleCommand(string const & cmd)
414 vector<string> const & possibles = possible_cite_commands();
415 vector<string>::const_iterator const end = possibles.end();
416 return find(possibles.begin(), end, cmd) != end;
420 docstring InsetCitation::generateLabel() const
422 docstring const before = getParam("before");
423 docstring const after = getParam("after");
426 biblio::CiteEngine const engine = buffer().params().getEngine();
427 label = getComplexLabel(buffer(), getCmdName(), getParam("key"),
428 before, after, engine);
430 // Fallback to fail-safe
432 label = getBasicLabel(getParam("key"), after);
438 docstring InsetCitation::screenLabel() const
440 return cache.screen_label;
444 void InsetCitation::updateLabels(ParIterator const &)
446 biblio::CiteEngine const engine = buffer().params().getEngine();
447 if (cache.params == params() && cache.engine == engine)
450 // The label has changed, so we have to re-create it.
451 docstring const glabel = generateLabel();
453 unsigned int const maxLabelChars = 45;
455 docstring label = glabel;
456 if (label.size() > maxLabelChars) {
457 label.erase(maxLabelChars-3);
461 cache.engine = engine;
462 cache.params = params();
463 cache.generated_label = glabel;
464 cache.screen_label = label;
468 void InsetCitation::addToToc(ParConstIterator const & cpit) const
470 Toc & toc = buffer().tocBackend().toc("citation");
471 toc.push_back(TocItem(cpit, 0, cache.screen_label));
475 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
477 os << cache.generated_label;
478 return cache.generated_label.size();
482 static docstring const cleanupWhitespace(docstring const & citelist)
484 docstring::const_iterator it = citelist.begin();
485 docstring::const_iterator end = citelist.end();
486 // Paranoia check: make sure that there is no whitespace in here
487 // -- at least not behind commas or at the beginning
489 char_type last = ',';
490 for (; it != end; ++it) {
493 if (*it != ' ' || last != ',')
500 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
502 os << from_ascii("<citation>")
503 << cleanupWhitespace(getParam("key"))
504 << from_ascii("</citation>");
509 void InsetCitation::textString(odocstream & os) const
511 plaintext(os, OutputParams(0));
515 // Have to overwrite the default InsetCommand method in order to check that
516 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
517 // citations and then changes his mind, turning natbib support off. The output
518 // should revert to \cite[]{}
519 int InsetCitation::latex(odocstream & os, OutputParams const &) const
521 biblio::CiteEngine cite_engine = buffer().params().getEngine();
523 docstring const cite_str = from_utf8(
524 asValidLatexCommand(getCmdName(), cite_engine));
526 os << "\\" << cite_str;
528 docstring const & before = getParam("before");
529 docstring const & after = getParam("after");
530 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
531 os << '[' << before << "][" << after << ']';
532 else if (!after.empty())
533 os << '[' << after << ']';
535 os << '{' << cleanupWhitespace(getParam("key")) << '}';
541 void InsetCitation::validate(LaTeXFeatures & features) const
543 switch (features.bufferParams().getEngine()) {
544 case biblio::ENGINE_BASIC:
546 case biblio::ENGINE_NATBIB_AUTHORYEAR:
547 case biblio::ENGINE_NATBIB_NUMERICAL:
548 features.require("natbib");
550 case biblio::ENGINE_JURABIB:
551 features.require("jurabib");