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"
16 #include "BiblioInfo.h"
18 #include "buffer_funcs.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "DispatchResult.h"
22 #include "LaTeXFeatures.h"
23 #include "output_xhtml.h"
24 #include "ParIterator.h"
25 #include "TocBackend.h"
27 #include "support/debug.h"
28 #include "support/docstream.h"
29 #include "support/FileNameList.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
36 using namespace lyx::support;
40 ParamInfo InsetCitation::param_info_;
43 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
44 : InsetCommand(buf, p)
48 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
50 // standard cite does only take one argument if jurabib is
51 // not used, but jurabib extends this to two arguments, so
52 // we have to allow both here. InsetCitation takes care that
53 // LaTeX output is nevertheless correct.
54 if (param_info_.empty()) {
55 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
56 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
57 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
65 vector<string> const init_possible_cite_commands()
67 char const * const possible[] = {
68 "cite", "nocite", "citet", "citep", "citealt", "citealp",
69 "citeauthor", "citeyear", "citeyearpar",
70 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
71 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
72 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
74 "footcite", "footcitet", "footcitep", "footcitealt",
75 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
76 "citefield", "citetitle", "cite*"
78 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
80 return vector<string>(possible, possible + size_possible);
84 vector<string> const & possibleCiteCommands()
86 static vector<string> const possible = init_possible_cite_commands();
94 bool InsetCitation::isCompatibleCommand(string const & cmd)
96 vector<string> const & possibles = possibleCiteCommands();
97 vector<string>::const_iterator const end = possibles.end();
98 return find(possibles.begin(), end, cmd) != end;
102 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
104 Buffer const & buf = bv.buffer();
105 // Only after the buffer is loaded from file...
106 if (!buf.isFullyLoaded())
109 BiblioInfo const & bi = buf.masterBibInfo();
111 return _("No bibliography defined!");
113 docstring const & key = getParam("key");
115 return _("No citations selected!");
117 vector<docstring> keys = getVectorFromString(key);
118 vector<docstring>::const_iterator it = keys.begin();
119 vector<docstring>::const_iterator en = keys.end();
121 for (; it != en; ++it) {
122 docstring const key_info = bi.getInfo(*it, buffer());
123 if (key_info.empty())
127 tip += wrap(key_info, -4);
135 // FIXME See the header for the issue.
136 string defaultCiteCommand(CiteEngine engine)
143 case ENGINE_NATBIB_AUTHORYEAR:
146 case ENGINE_NATBIB_NUMERICAL:
157 string asValidLatexCommand(string const & input, CiteEngine const engine)
159 string const default_str = defaultCiteCommand(engine);
160 if (!InsetCitation::isCompatibleCommand(input))
166 if (input == "nocite")
169 output = default_str;
172 case ENGINE_NATBIB_AUTHORYEAR:
173 case ENGINE_NATBIB_NUMERICAL:
174 if (input == "cite" || input == "citefield"
175 || input == "citetitle" || input == "cite*")
176 output = default_str;
177 else if (prefixIs(input, "foot"))
178 output = input.substr(4);
183 case ENGINE_JURABIB: {
184 // Jurabib does not support the 'uppercase' natbib style.
186 output = string(1, 'c') + input.substr(1);
190 // Jurabib does not support the 'full' natbib style.
191 string::size_type const n = output.size() - 1;
192 if (output != "cite*" && output[n] == '*')
193 output = output.substr(0, n);
203 inline docstring wrapCitation(docstring const & key,
204 docstring const & content, bool for_xhtml)
208 // we have to do the escaping here, because we will ultimately
209 // write this as a raw string, so as not to escape the tags.
210 return "<a href='#" + key + "'>" +
211 html::htmlize(content, XHTMLStream::ESCAPE_ALL) + "</a>";
214 } // anonymous namespace
216 docstring InsetCitation::generateLabel(bool for_xhtml) const
219 label = complexLabel(for_xhtml);
221 // Fallback to fail-safe
223 label = basicLabel(for_xhtml);
229 docstring InsetCitation::complexLabel(bool for_xhtml) const
231 Buffer const & buf = buffer();
232 // Only start the process off after the buffer is loaded from file.
233 if (!buf.isFullyLoaded())
236 BiblioInfo const & biblist = buf.masterBibInfo();
240 // the natbib citation-styles
241 // CITET: author (year)
242 // CITEP: (author,year)
243 // CITEALT: author year
244 // CITEALP: author, year
245 // CITEAUTHOR: author
247 // CITEYEARPAR: (year)
248 // jurabib supports these plus
249 // CITE: author/<before field>
251 CiteEngine const engine = buffer().params().citeEngine();
252 // We don't currently use the full or forceUCase fields.
253 string cite_type = asValidLatexCommand(getCmdName(), engine);
254 if (cite_type[0] == 'C')
255 // If we were going to use them, this would mean ForceUCase
256 cite_type = string(1, 'c') + cite_type.substr(1);
257 if (cite_type[cite_type.size() - 1] == '*')
258 // and this would mean FULL
259 cite_type = cite_type.substr(0, cite_type.size() - 1);
261 docstring const & before = getParam("before");
262 docstring before_str;
263 if (!before.empty()) {
264 // In CITET and CITEALT mode, the "before" string is
265 // attached to the label associated with each and every key.
266 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
267 // to the front of the whole only.
268 // In other modes, it is not used at all.
269 if (cite_type == "citet" ||
270 cite_type == "citealt" ||
271 cite_type == "citep" ||
272 cite_type == "citealp" ||
273 cite_type == "citeyearpar")
274 before_str = before + ' ';
275 // In CITE (jurabib), the "before" string is used to attach
276 // the annotator (of legal texts) to the author(s) of the
278 else if (cite_type == "cite")
279 before_str = '/' + before;
282 docstring const & after = getParam("after");
284 // The "after" key is appended only to the end of the whole.
285 if (cite_type == "nocite")
286 after_str = " (" + _("not cited") + ')';
287 else if (!after.empty()) {
288 after_str = ", " + after;
291 // One day, these might be tunable (as they are in BibTeX).
292 char op, cp; // opening and closing parenthesis.
293 const char * sep; // punctuation mark separating citation entries.
294 if (engine == ENGINE_BASIC) {
304 docstring const op_str = ' ' + docstring(1, op);
305 docstring const cp_str = docstring(1, cp) + ' ';
306 docstring const sep_str = from_ascii(sep) + ' ';
309 vector<docstring> keys = getVectorFromString(getParam("key"));
310 vector<docstring>::const_iterator it = keys.begin();
311 vector<docstring>::const_iterator end = keys.end();
312 for (; it != end; ++it) {
313 // get the bibdata corresponding to the key
314 docstring const author = biblist.getAbbreviatedAuthor(*it);
315 docstring const year = biblist.getYear(*it, for_xhtml);
316 docstring const citenum = for_xhtml ? biblist.getCiteNumber(*it) : *it;
318 if (author.empty() || year.empty())
319 // We can't construct a "complex" label without that info.
323 // authors1/<before>; ... ;
324 // authors_last, <after>
325 if (cite_type == "cite") {
326 if (engine == ENGINE_BASIC) {
327 label += wrapCitation(*it, citenum, for_xhtml) + sep_str;
328 } else if (engine == ENGINE_JURABIB) {
329 if (it == keys.begin())
330 label += wrapCitation(*it, author, for_xhtml) + before_str + sep_str;
332 label += wrapCitation(*it, author, for_xhtml) + sep_str;
336 else if (cite_type == "nocite") {
337 label += *it + sep_str;
339 // (authors1 (<before> year); ... ;
340 // authors_last (<before> year, <after>)
341 else if (cite_type == "citet") {
343 case ENGINE_NATBIB_AUTHORYEAR:
344 label += author + op_str + before_str +
345 wrapCitation(*it, year, for_xhtml) + cp + sep_str;
347 case ENGINE_NATBIB_NUMERICAL:
348 label += author + op_str + before_str +
349 wrapCitation(*it, citenum, for_xhtml) + cp + sep_str;
352 label += before_str + author + op_str +
353 wrapCitation(*it, year, for_xhtml) + cp + sep_str;
359 // author, year; author, year; ...
360 else if (cite_type == "citep" ||
361 cite_type == "citealp") {
362 if (engine == ENGINE_NATBIB_NUMERICAL) {
363 label += wrapCitation(*it, citenum, for_xhtml) + sep_str;
365 label += wrapCitation(*it, author + ", " + year, for_xhtml) + sep_str;
369 // (authors1 <before> year;
370 // authors_last <before> year, <after>)
371 else if (cite_type == "citealt") {
373 case ENGINE_NATBIB_AUTHORYEAR:
374 label += author + ' ' + before_str +
375 wrapCitation(*it, year, for_xhtml) + sep_str;
377 case ENGINE_NATBIB_NUMERICAL:
378 label += author + ' ' + before_str + '#' +
379 wrapCitation(*it, citenum, for_xhtml) + sep_str;
382 label += before_str +
383 wrapCitation(*it, author + ' ' + year, for_xhtml) + sep_str;
391 // author; author; ...
392 else if (cite_type == "citeauthor") {
393 label += wrapCitation(*it, author, for_xhtml) + sep_str;
396 else if (cite_type == "citeyear" ||
397 cite_type == "citeyearpar") {
398 label += wrapCitation(*it, year, for_xhtml) + sep_str;
401 label = rtrim(rtrim(label), sep);
403 if (!after_str.empty()) {
404 if (cite_type == "citet") {
405 // insert "after" before last ')'
406 label.insert(label.size() - 1, after_str);
409 !(engine == ENGINE_NATBIB_NUMERICAL &&
410 (cite_type == "citeauthor" ||
411 cite_type == "citeyear"));
417 if (!before_str.empty() && (cite_type == "citep" ||
418 cite_type == "citealp" ||
419 cite_type == "citeyearpar")) {
420 label = before_str + label;
423 if (cite_type == "citep" || cite_type == "citeyearpar" ||
424 (cite_type == "cite" && engine == ENGINE_BASIC) )
425 label = op + label + cp;
431 docstring InsetCitation::basicLabel(bool for_xhtml) const
433 docstring keys = getParam("key");
438 // if there is no comma, then everything goes into key
439 // and keys will be empty.
440 keys = trim(split(keys, key, ','));
444 label += wrapCitation(key, key, for_xhtml);
445 } while (!keys.empty());
447 docstring const & after = getParam("after");
449 label += ", " + after;
451 return '[' + label + ']';
454 docstring InsetCitation::screenLabel() const
456 return cache.screen_label;
460 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
462 CiteEngine const engine = buffer().params().citeEngine();
463 if (cache.params == params() && cache.engine == engine)
466 // The label has changed, so we have to re-create it.
467 docstring const glabel = generateLabel();
469 unsigned int const maxLabelChars = 45;
471 docstring label = glabel;
472 if (label.size() > maxLabelChars) {
473 label.erase(maxLabelChars - 3);
477 cache.engine = engine;
478 cache.params = params();
479 cache.generated_label = glabel;
480 cache.screen_label = label;
484 void InsetCitation::addToToc(DocIterator const & cpit) const
487 // XHTML output uses the TOC to collect the citations
488 // from the document. So if this gets changed, then we
489 // will need to change how the citations are collected.
490 docstring const tocitem = getParam("key");
491 Toc & toc = buffer().tocBackend().toc("citation");
492 toc.push_back(TocItem(cpit, 0, tocitem));
496 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
498 os << cache.generated_label;
499 return cache.generated_label.size();
503 static docstring const cleanupWhitespace(docstring const & citelist)
505 docstring::const_iterator it = citelist.begin();
506 docstring::const_iterator end = citelist.end();
507 // Paranoia check: make sure that there is no whitespace in here
508 // -- at least not behind commas or at the beginning
510 char_type last = ',';
511 for (; it != end; ++it) {
514 if (*it != ' ' || last != ',')
521 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
523 os << from_ascii("<citation>")
524 << cleanupWhitespace(getParam("key"))
525 << from_ascii("</citation>");
530 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
532 string const & cmd = getCmdName();
536 // have to output this raw, because generateLabel() will include tags
537 xs << XHTMLStream::ESCAPE_NONE << generateLabel(true);
543 void InsetCitation::toString(odocstream & os) const
545 plaintext(os, OutputParams(0));
549 void InsetCitation::forToc(docstring & os, size_t) const
555 // Have to overwrite the default InsetCommand method in order to check that
556 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
557 // citations and then changes his mind, turning natbib support off. The output
558 // should revert to \cite[]{}
559 void InsetCitation::latex(otexstream & os, OutputParams const & runparams) const
561 CiteEngine cite_engine = buffer().params().citeEngine();
562 BiblioInfo const & bi = buffer().masterBibInfo();
564 docstring const cite_str = from_utf8(
565 asValidLatexCommand(getCmdName(), cite_engine));
567 if (runparams.inulemcmd)
570 os << "\\" << cite_str;
572 docstring const & before = getParam("before");
573 docstring const & after = getParam("after");
574 if (!before.empty() && cite_engine != ENGINE_BASIC)
575 os << '[' << before << "][" << after << ']';
576 else if (!after.empty())
577 os << '[' << after << ']';
579 if (!bi.isBibtex(getParam("key")))
580 // escape chars with bibitems
581 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
583 os << '{' << cleanupWhitespace(getParam("key")) << '}';
585 if (runparams.inulemcmd)
590 void InsetCitation::validate(LaTeXFeatures & features) const
592 switch (features.bufferParams().citeEngine()) {
595 case ENGINE_NATBIB_AUTHORYEAR:
596 case ENGINE_NATBIB_NUMERICAL:
597 features.require("natbib");
600 features.require("jurabib");
606 docstring InsetCitation::contextMenuName() const
608 return from_ascii("context-citation");