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 & possibleCiteCommands()
61 static vector<string> const possible = init_possible_cite_commands();
66 // FIXME See the header for the issue.
67 string defaultCiteCommand(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:
88 string asValidLatexCommand(string const & input, biblio::CiteEngine const engine)
90 string const default_str = defaultCiteCommand(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 complexLabel(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 basicLabel(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, ','));
373 label += ", " + after;
375 return '[' + label + ']';
381 ParamInfo InsetCitation::param_info_;
384 InsetCitation::InsetCitation(InsetCommandParams const & p)
385 : InsetCommand(p, "citation")
389 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
391 // standard cite does only take one argument if jurabib is
392 // not used, but jurabib extends this to two arguments, so
393 // we have to allow both here. InsetCitation takes care that
394 // LaTeX output is nevertheless correct.
395 if (param_info_.empty()) {
396 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
397 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
398 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
404 bool InsetCitation::isCompatibleCommand(string const & cmd)
406 vector<string> const & possibles = possibleCiteCommands();
407 vector<string>::const_iterator const end = possibles.end();
408 return find(possibles.begin(), end, cmd) != end;
412 docstring InsetCitation::generateLabel() const
414 docstring const before = getParam("before");
415 docstring const after = getParam("after");
418 biblio::CiteEngine const engine = buffer().params().citeEngine();
419 label = complexLabel(buffer(), getCmdName(), getParam("key"),
420 before, after, engine);
422 // Fallback to fail-safe
424 label = basicLabel(getParam("key"), after);
430 docstring InsetCitation::screenLabel() const
432 return cache.screen_label;
436 void InsetCitation::updateLabels(ParIterator const &)
438 biblio::CiteEngine const engine = buffer().params().citeEngine();
439 if (cache.params == params() && cache.engine == engine)
442 // The label has changed, so we have to re-create it.
443 docstring const glabel = generateLabel();
445 unsigned int const maxLabelChars = 45;
447 docstring label = glabel;
448 if (label.size() > maxLabelChars) {
449 label.erase(maxLabelChars-3);
453 cache.engine = engine;
454 cache.params = params();
455 cache.generated_label = glabel;
456 cache.screen_label = label;
460 void InsetCitation::addToToc(ParConstIterator const & cpit) const
462 Toc & toc = buffer().tocBackend().toc("citation");
463 toc.push_back(TocItem(cpit, 0, cache.screen_label));
467 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
469 os << cache.generated_label;
470 return cache.generated_label.size();
474 static docstring const cleanupWhitespace(docstring const & citelist)
476 docstring::const_iterator it = citelist.begin();
477 docstring::const_iterator end = citelist.end();
478 // Paranoia check: make sure that there is no whitespace in here
479 // -- at least not behind commas or at the beginning
481 char_type last = ',';
482 for (; it != end; ++it) {
485 if (*it != ' ' || last != ',')
492 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
494 os << from_ascii("<citation>")
495 << cleanupWhitespace(getParam("key"))
496 << from_ascii("</citation>");
501 void InsetCitation::textString(odocstream & os) const
503 plaintext(os, OutputParams(0));
507 // Have to overwrite the default InsetCommand method in order to check that
508 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
509 // citations and then changes his mind, turning natbib support off. The output
510 // should revert to \cite[]{}
511 int InsetCitation::latex(odocstream & os, OutputParams const &) const
513 biblio::CiteEngine cite_engine = buffer().params().citeEngine();
515 docstring const cite_str = from_utf8(
516 asValidLatexCommand(getCmdName(), cite_engine));
518 os << "\\" << cite_str;
520 docstring const & before = getParam("before");
521 docstring const & after = getParam("after");
522 if (!before.empty() && cite_engine != biblio::ENGINE_BASIC)
523 os << '[' << before << "][" << after << ']';
524 else if (!after.empty())
525 os << '[' << after << ']';
527 os << '{' << cleanupWhitespace(getParam("key")) << '}';
533 void InsetCitation::validate(LaTeXFeatures & features) const
535 switch (features.bufferParams().citeEngine()) {
536 case biblio::ENGINE_BASIC:
538 case biblio::ENGINE_NATBIB_AUTHORYEAR:
539 case biblio::ENGINE_NATBIB_NUMERICAL:
540 features.require("natbib");
542 case biblio::ENGINE_JURABIB:
543 features.require("jurabib");