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 "BufferView.h"
20 #include "DispatchResult.h"
21 #include "LaTeXFeatures.h"
22 #include "output_xhtml.h"
23 #include "ParIterator.h"
24 #include "TocBackend.h"
26 #include "support/debug.h"
27 #include "support/docstream.h"
28 #include "support/FileNameList.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
35 using namespace lyx::support;
39 ParamInfo InsetCitation::param_info_;
42 InsetCitation::InsetCitation(Buffer * buf, InsetCommandParams const & p)
43 : InsetCommand(buf, p, "citation")
47 ParamInfo const & InsetCitation::findInfo(string const & /* cmdName */)
49 // standard cite does only take one argument if jurabib is
50 // not used, but jurabib extends this to two arguments, so
51 // we have to allow both here. InsetCitation takes care that
52 // LaTeX output is nevertheless correct.
53 if (param_info_.empty()) {
54 param_info_.add("after", ParamInfo::LATEX_OPTIONAL);
55 param_info_.add("before", ParamInfo::LATEX_OPTIONAL);
56 param_info_.add("key", ParamInfo::LATEX_REQUIRED);
64 vector<string> const init_possible_cite_commands()
66 char const * const possible[] = {
67 "cite", "nocite", "citet", "citep", "citealt", "citealp",
68 "citeauthor", "citeyear", "citeyearpar",
69 "citet*", "citep*", "citealt*", "citealp*", "citeauthor*",
70 "Citet", "Citep", "Citealt", "Citealp", "Citeauthor",
71 "Citet*", "Citep*", "Citealt*", "Citealp*", "Citeauthor*",
73 "footcite", "footcitet", "footcitep", "footcitealt",
74 "footcitealp", "footciteauthor", "footciteyear", "footciteyearpar",
75 "citefield", "citetitle", "cite*"
77 size_t const size_possible = sizeof(possible) / sizeof(possible[0]);
79 return vector<string>(possible, possible + size_possible);
83 vector<string> const & possibleCiteCommands()
85 static vector<string> const possible = init_possible_cite_commands();
93 bool InsetCitation::isCompatibleCommand(string const & cmd)
95 vector<string> const & possibles = possibleCiteCommands();
96 vector<string>::const_iterator const end = possibles.end();
97 return find(possibles.begin(), end, cmd) != end;
101 docstring InsetCitation::toolTip(BufferView const & bv, int, int) const
103 Buffer const & buf = bv.buffer();
104 // Only after the buffer is loaded from file...
105 if (!buf.isFullyLoaded())
108 BiblioInfo const & bi = buf.masterBibInfo();
110 return _("No bibliography defined!");
112 docstring const & key = getParam("key");
114 return _("No citations selected!");
116 vector<docstring> keys = getVectorFromString(key);
117 vector<docstring>::const_iterator it = keys.begin();
118 vector<docstring>::const_iterator en = keys.end();
120 for (; it != en; ++it) {
121 docstring const key_info = bi.getInfo(*it, buffer());
122 if (key_info.empty())
126 tip += wrap(key_info, -4);
134 // FIXME See the header for the issue.
135 string defaultCiteCommand(CiteEngine engine)
142 case ENGINE_NATBIB_AUTHORYEAR:
145 case ENGINE_NATBIB_NUMERICAL:
156 string asValidLatexCommand(string const & input, CiteEngine const engine)
158 string const default_str = defaultCiteCommand(engine);
159 if (!InsetCitation::isCompatibleCommand(input))
165 if (input == "nocite")
168 output = default_str;
171 case ENGINE_NATBIB_AUTHORYEAR:
172 case ENGINE_NATBIB_NUMERICAL:
173 if (input == "cite" || input == "citefield"
174 || input == "citetitle" || input == "cite*")
175 output = default_str;
176 else if (prefixIs(input, "foot"))
177 output = input.substr(4);
182 case ENGINE_JURABIB: {
183 // Jurabib does not support the 'uppercase' natbib style.
185 output = string(1, 'c') + input.substr(1);
189 // Jurabib does not support the 'full' natbib style.
190 string::size_type const n = output.size() - 1;
191 if (output != "cite*" && output[n] == '*')
192 output = output.substr(0, n);
202 inline docstring wrapCitation(docstring const & key,
203 docstring const & content, bool for_xhtml)
207 // we have to do the escaping here, because we will ultimately
208 // write this as a raw string, so as not to escape the tags.
209 return "<a href='#" + key + "'>" + html::htmlize(content) + "</a>";
212 } // anonymous namespace
214 docstring InsetCitation::generateLabel(bool for_xhtml) const
217 label = complexLabel(for_xhtml);
219 // Fallback to fail-safe
221 label = basicLabel(for_xhtml);
227 docstring InsetCitation::complexLabel(bool for_xhtml) const
229 Buffer const & buf = buffer();
230 // Only start the process off after the buffer is loaded from file.
231 if (!buf.isFullyLoaded())
234 BiblioInfo const & biblist = buf.masterBibInfo();
238 // the natbib citation-styles
239 // CITET: author (year)
240 // CITEP: (author,year)
241 // CITEALT: author year
242 // CITEALP: author, year
243 // CITEAUTHOR: author
245 // CITEYEARPAR: (year)
246 // jurabib supports these plus
247 // CITE: author/<before field>
249 CiteEngine const engine = buffer().params().citeEngine();
250 // We don't currently use the full or forceUCase fields.
251 string cite_type = asValidLatexCommand(getCmdName(), engine);
252 if (cite_type[0] == 'C')
253 // If we were going to use them, this would mean ForceUCase
254 cite_type = string(1, 'c') + cite_type.substr(1);
255 if (cite_type[cite_type.size() - 1] == '*')
256 // and this would mean FULL
257 cite_type = cite_type.substr(0, cite_type.size() - 1);
259 docstring const & before = getParam("before");
260 docstring before_str;
261 if (!before.empty()) {
262 // In CITET and CITEALT mode, the "before" string is
263 // attached to the label associated with each and every key.
264 // In CITEP, CITEALP and CITEYEARPAR mode, it is attached
265 // to the front of the whole only.
266 // In other modes, it is not used at all.
267 if (cite_type == "citet" ||
268 cite_type == "citealt" ||
269 cite_type == "citep" ||
270 cite_type == "citealp" ||
271 cite_type == "citeyearpar")
272 before_str = before + ' ';
273 // In CITE (jurabib), the "before" string is used to attach
274 // the annotator (of legal texts) to the author(s) of the
276 else if (cite_type == "cite")
277 before_str = '/' + before;
280 docstring const & after = getParam("after");
282 // The "after" key is appended only to the end of the whole.
283 if (cite_type == "nocite")
284 after_str = " (" + _("not cited") + ')';
285 else if (!after.empty()) {
286 after_str = ", " + after;
289 // One day, these might be tunable (as they are in BibTeX).
290 char op, cp; // opening and closing parenthesis.
291 const char * sep; // punctuation mark separating citation entries.
292 if (engine == ENGINE_BASIC) {
302 docstring const op_str = ' ' + docstring(1, op);
303 docstring const cp_str = docstring(1, cp) + ' ';
304 docstring const sep_str = from_ascii(sep) + ' ';
307 vector<docstring> keys = getVectorFromString(getParam("key"));
308 vector<docstring>::const_iterator it = keys.begin();
309 vector<docstring>::const_iterator end = keys.end();
310 for (; it != end; ++it) {
311 // get the bibdata corresponding to the key
312 docstring const author = biblist.getAbbreviatedAuthor(*it);
313 docstring const year = biblist.getYear(*it, for_xhtml);
314 docstring const citenum = for_xhtml ? biblist.getCiteNumber(*it) : *it;
316 if (author.empty() || year.empty())
317 // We can't construct a "complex" label without that info.
321 // authors1/<before>; ... ;
322 // authors_last, <after>
323 if (cite_type == "cite") {
324 if (engine == ENGINE_BASIC) {
325 label += wrapCitation(*it, citenum, for_xhtml) + sep_str;
326 } else if (engine == ENGINE_JURABIB) {
327 if (it == keys.begin())
328 label += wrapCitation(*it, author, for_xhtml) + before_str + sep_str;
330 label += wrapCitation(*it, author, for_xhtml) + sep_str;
334 else if (cite_type == "nocite") {
335 label += *it + sep_str;
337 // (authors1 (<before> year); ... ;
338 // authors_last (<before> year, <after>)
339 else if (cite_type == "citet") {
341 case ENGINE_NATBIB_AUTHORYEAR:
342 label += author + op_str + before_str +
343 wrapCitation(*it, year, for_xhtml) + cp + sep_str;
345 case ENGINE_NATBIB_NUMERICAL:
346 label += author + op_str + before_str +
347 wrapCitation(*it, citenum, for_xhtml) + cp + sep_str;
350 label += before_str + author + op_str +
351 wrapCitation(*it, year, for_xhtml) + cp + sep_str;
357 // author, year; author, year; ...
358 else if (cite_type == "citep" ||
359 cite_type == "citealp") {
360 if (engine == ENGINE_NATBIB_NUMERICAL) {
361 label += wrapCitation(*it, citenum, for_xhtml) + sep_str;
363 label += wrapCitation(*it, author + ", " + year, for_xhtml) + sep_str;
367 // (authors1 <before> year;
368 // authors_last <before> year, <after>)
369 else if (cite_type == "citealt") {
371 case ENGINE_NATBIB_AUTHORYEAR:
372 label += author + ' ' + before_str +
373 wrapCitation(*it, year, for_xhtml) + sep_str;
375 case ENGINE_NATBIB_NUMERICAL:
376 label += author + ' ' + before_str + '#' +
377 wrapCitation(*it, citenum, for_xhtml) + sep_str;
380 label += before_str +
381 wrapCitation(*it, author + ' ' + year, for_xhtml) + sep_str;
389 // author; author; ...
390 else if (cite_type == "citeauthor") {
391 label += wrapCitation(*it, author, for_xhtml) + sep_str;
394 else if (cite_type == "citeyear" ||
395 cite_type == "citeyearpar") {
396 label += wrapCitation(*it, year, for_xhtml) + sep_str;
399 label = rtrim(rtrim(label), sep);
401 if (!after_str.empty()) {
402 if (cite_type == "citet") {
403 // insert "after" before last ')'
404 label.insert(label.size() - 1, after_str);
407 !(engine == ENGINE_NATBIB_NUMERICAL &&
408 (cite_type == "citeauthor" ||
409 cite_type == "citeyear"));
415 if (!before_str.empty() && (cite_type == "citep" ||
416 cite_type == "citealp" ||
417 cite_type == "citeyearpar")) {
418 label = before_str + label;
421 if (cite_type == "citep" || cite_type == "citeyearpar" ||
422 (cite_type == "cite" && engine == ENGINE_BASIC) )
423 label = op + label + cp;
429 docstring InsetCitation::basicLabel(bool for_xhtml) const
431 docstring keys = getParam("key");
436 // if there is no comma, then everything goes into key
437 // and keys will be empty.
438 keys = trim(split(keys, key, ','));
442 label += wrapCitation(key, key, for_xhtml);
443 } while (!keys.empty());
445 docstring const & after = getParam("after");
447 label += ", " + after;
449 return '[' + label + ']';
452 docstring InsetCitation::screenLabel() const
454 return cache.screen_label;
458 void InsetCitation::updateBuffer(ParIterator const &, UpdateType)
460 CiteEngine const engine = buffer().params().citeEngine();
461 if (cache.params == params() && cache.engine == engine)
464 // The label has changed, so we have to re-create it.
465 docstring const glabel = generateLabel();
467 unsigned int const maxLabelChars = 45;
469 docstring label = glabel;
470 if (label.size() > maxLabelChars) {
471 label.erase(maxLabelChars - 3);
475 cache.engine = engine;
476 cache.params = params();
477 cache.generated_label = glabel;
478 cache.screen_label = label;
482 void InsetCitation::addToToc(DocIterator const & cpit)
485 // XHTML output uses the TOC to collect the citations
486 // from the document. So if this gets changed, then we
487 // will need to change how the citations are collected.
488 docstring const tocitem = getParam("key");
489 Toc & toc = buffer().tocBackend().toc("citation");
490 toc.push_back(TocItem(cpit, 0, tocitem));
494 int InsetCitation::plaintext(odocstream & os, OutputParams const &) const
496 os << cache.generated_label;
497 return cache.generated_label.size();
501 static docstring const cleanupWhitespace(docstring const & citelist)
503 docstring::const_iterator it = citelist.begin();
504 docstring::const_iterator end = citelist.end();
505 // Paranoia check: make sure that there is no whitespace in here
506 // -- at least not behind commas or at the beginning
508 char_type last = ',';
509 for (; it != end; ++it) {
512 if (*it != ' ' || last != ',')
519 int InsetCitation::docbook(odocstream & os, OutputParams const &) const
521 os << from_ascii("<citation>")
522 << cleanupWhitespace(getParam("key"))
523 << from_ascii("</citation>");
528 docstring InsetCitation::xhtml(XHTMLStream & xs, OutputParams const &) const
530 string const & cmd = getCmdName();
534 // have to output this raw, because generateLabel() will include tags
535 xs << XHTMLStream::NextRaw() << generateLabel(true);
541 void InsetCitation::tocString(odocstream & os) const
543 plaintext(os, OutputParams(0));
547 // Have to overwrite the default InsetCommand method in order to check that
548 // the \cite command is valid. Eg, the user has natbib enabled, inputs some
549 // citations and then changes his mind, turning natbib support off. The output
550 // should revert to \cite[]{}
551 int InsetCitation::latex(odocstream & os, OutputParams const & runparams) const
553 CiteEngine cite_engine = buffer().params().citeEngine();
554 BiblioInfo const & bi = buffer().masterBibInfo();
556 docstring const cite_str = from_utf8(
557 asValidLatexCommand(getCmdName(), cite_engine));
559 if (runparams.inulemcmd)
562 os << "\\" << cite_str;
564 docstring const & before = getParam("before");
565 docstring const & after = getParam("after");
566 if (!before.empty() && cite_engine != ENGINE_BASIC)
567 os << '[' << before << "][" << after << ']';
568 else if (!after.empty())
569 os << '[' << after << ']';
571 if (!bi.isBibtex(getParam("key")))
572 // escape chars with bibitems
573 os << '{' << escape(cleanupWhitespace(getParam("key"))) << '}';
575 os << '{' << cleanupWhitespace(getParam("key")) << '}';
577 if (runparams.inulemcmd)
584 void InsetCitation::validate(LaTeXFeatures & features) const
586 switch (features.bufferParams().citeEngine()) {
589 case ENGINE_NATBIB_AUTHORYEAR:
590 case ENGINE_NATBIB_NUMERICAL:
591 features.require("natbib");
594 features.require("jurabib");
600 docstring InsetCitation::contextMenu(BufferView const &, int, int) const
602 return from_ascii("context-citation");